2

我有以下应用程序。一部电影有很多评论,一个电影观众有很多评论。当我尝试将评论与电影相关联时,出现以下错误

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

评论.rb

class Review < ActiveRecord::Base
  belongs_to :movie
  belongs_to :moviegoer
  attr_protected :moviegoer_id
end

movie.rb 和 moviegoer.rb 有

has_many :评论

在他们中。架构.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查询“reviews”。“movie_id”而不仅仅是“movie_id”?

4

1 回答 1

3

您在迁移中使用了错误的列名。rails 的约定是外键是单数的。如果不是,那么您需要通过关联上的选项散列告诉 Rails 外键是什么。

要么回滚你的迁移,修复列名(moviegoers_id 也是错误的)然后再次迁移,或者告诉 rails 外键。

Class Review < ActiveRecord::Base
  belongs_to :movie, :foreign_key => 'movies_id'
  belongs_to :moviegoer, :foreign_key => 'moviegoers_id'
end

两种模型的许多方面都必须发生同样的情况。

于 2013-02-22T23:52:25.243 回答