gpt4 book ai didi

mysql - 当列存在时,为什么我会得到未知列?

转载 作者:行者123 更新时间:2023-11-29 11:43:11 25 4
gpt4 key购买 nike

当运行 photos#star 的规范时,我不确定为什么当该列实际存在时,会出现 Stars.user_id 的未知列错误。该操作在 Rails 控制台和浏览器中运行良好,因为 @user.starred_photos 实际上已被修改。

我检查了 mysql 中的数据库架构,该列就在那里。我尝试回滚迁移并重做它以及重新启动服务器。这是错误:

Failure/Error:
expect{
post :star, id: photo
}.to change{ @user.starred_photos.count }.from(0).to(1)

ActiveRecord::StatementInvalid:
Mysql2::Error: Unknown column 'stars.user_id' in 'where clause': SELECT COUNT(*) FROM `photos` INNER JOIN `stars` ON `photos`.`id` = `stars`.`photo_id` WHERE `stars`.`user_id` = 1

Controller 规范和操作

# spec/controllers/photos_controller_spec.rb   
describe '#POST star' do
it "adds the given photo to the user's starred photos" do
sign_in_as_user
other_user = create(:user)
photo = other_user.photos.create(attributes_for(:photo))

expect{
post :star, id: photo
}.to change{ @user.starred_photos.count }.from(0).to(1)
end
end


#app/controllers/photos_controller.rb
def star
current_user.starred_photos << @photo
end

型号

# app/models/star.rb
class Star < ActiveRecord::Base
belongs_to :user
belongs_to :photo
end

# app/models/user.rb
class User < ActiveRecord::Base
has_many :photos
has_many :stars
has_many :starred_photos, through: :stars, source: :photo

# app/models/photo.rb
class Photo < ActiveRecord::Base
belongs_to :user
has_many :stars
has_many :starring_users, through: :stars, source: :user

架构

# db/schema.rb
create_table "stars", force: :cascade do |t|
t.integer "photo_id", limit: 4
t.integer "user_id", limit: 4
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

我正在经历这样的日子,我怀疑我在这里错过了一些非常明显的东西。提前致谢!

最佳答案

您的测试数据库可能尚未应用迁移。您可以运行 rake db:test:prepare 将开发数据库架构复制到测试数据库,然后尝试再次运行测试。或者,您可以只运行 rake spec - 默认情况下,该命令将在运行任何测试之前准备您的测试数据库。

关于mysql - 当列存在时,为什么我会得到未知列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com