【发布时间】:2016-02-15 18:48:17
【问题描述】:
在运行我的照片#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
控制器规格和操作
# 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
我正经历着这样的一天,我怀疑我在这里遗漏了一些非常明显的东西。提前致谢!
【问题讨论】:
-
你能出示你的
database.yml文件吗? -
检查你的mysql版本和你正在使用的gem版本。过去我也遇到过类似的问题,通常重启 mysql 服务会暂时为我解决。从未调查过导致问题的原因,但更新到最后一个 mysql / mysql2 gem 解决了它。
-
尝试运行
rake db:test:prepare以从您的开发数据库更新您的测试架构。 -
感谢大家的回复,@RobertNube 的建议非常有效。如果其他人像我一样被卡住,我希望其他人能从他的评论中受益。
-
@SajadTorkamani:很酷。为了后代,我写了评论作为答案,并提供了更多细节。
标签: mysql ruby-on-rails rspec rails-migrations