所以我的应用程序中有三个模型,一个是User,Review和一个Movie模型。用户可以查看许多电影(每部电影一部),电影可以有许多用户的评论。他们的联系是一个审查。
我正在进行以下设置吗?
class Movie < ActiveRecord::Base
has_many :reviews, :through => :users
end
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
class User < ActiveRecord::Base
has_many :reviews, :through => :movies
end
我希望我可以做类似的事情:
User.reviews
(这会让我回复用户的评论以及与评论相关的电影的相应ID)
由于
答案 0 :(得分:1)
我相信这是你应该采取的方法
class User < ActiveRecord::Base
has_many :reviews
has_many :movies, :through => :reviews
end
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :movie
end
class Movie < ActiveRecord::Base
has_many :reviews
has_many :users, :through => :reviews
end
您还希望验证模型Review
中的唯一性和/或强制连接表上的唯一性,以便每个影片只允许一个用户。如果你想把这个UQ约束带入模式,这取决于你(DHH说'是',我说'愚蠢的持久性'是'不可'......)
User.reviews
将为您提供“加入记录”,即<Review user_id=x, movie_id=y>
行。当然,您在联接表上有更多与审核相关的列,例如{{ 1}}等。从评论中访问电影很容易,即:summary, :content