我有以下应用。电影有很多评论,电影观众有很多评论。 当我尝试将评论与电影相关联时,我收到以下错误
Review Load (0.1ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."movie_id" = 5
SQLite3::SQLException: no such column: reviews.movie_id: SELECT "reviews".* FROM "reviews" WHERE "reviews"."movie_id" = 5
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: reviews.movie_id: SELECT "reviews".* FROM "reviews" WHERE "reviews"."movie_id" = 5
使用sql gui编辑器后,我发现正确的查询应该是
SELECT "reviews".* FROM "reviews" WHERE "movie_id" = 5
review.rb
class Review < ActiveRecord::Base
belongs_to :movie
belongs_to :moviegoer
attr_protected :moviegoer_id
end
movie.rb和moviegoer.rb有
has_many:评论
在他们中间。 schema.rb
ActiveRecord::Schema.define(:version => 20130222225620) do
create_table "moviegoers", :force => true do |t|
t.string "name"
t.string "provider"
t.string "uid"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "movies", :force => true do |t|
t.string "title"
t.string "rating"
t.text "description"
t.datetime "release_date"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "reviews", :force => true do |t|
t.integer "potatoes"
t.text "comments"
t.integer "moviegoers_id"
t.integer "movies_id"
end
end
我做错了什么?为什么rails会查询“评论”。“movie_id”而不仅仅是“movie_id”?
答案 0 :(得分:2)
迁移中的列名错误。 rails常规是外键是单数的。如果它们不是那么你需要通过关联的选项哈希告诉rails外键是什么。
要么回滚迁移,修复列名称(moviegoers_id也是错误的),然后再次迁移,或者告诉rails外键。
Class Review < ActiveRecord::Base
belongs_to :movie, :foreign_key => 'movies_id'
belongs_to :moviegoer, :foreign_key => 'moviegoers_id'
end
同样必须发生在两个模型的许多方面。