简体   繁体   English

在Rails中建立多对多关联的正确方法是什么

[英]What is the right way to set up a many to many association in Rails

So I've got three models in my app, a User, Review and a Movie model. 所以我的应用程序中有三个模型,一个用户模型,一个评论模型和一个电影模型。 A user can review many movies (one per movie), a Movie can have many reviews from many users. 用户可以查看许多电影(每个电影一个),电影可以有许多用户的许多评论。 Their connection is a review. 他们的联系是一个评论。

Am I doing the following setup right? 我是否正确设置以下设置?

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

I'm hoping I can do something like: 我希望我可以做类似的事情:

User.reviews (which would give me back the user's reviews and the corresponding id of the movie which the review relates to) User.reviews (可以将用户的评论以及与该评论相关的电影的对应ID退还给我)

Thanks 谢谢

I believe this is the approach you should be taking 我相信这是您应该采取的方法

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

You would also want to validate uniqueness in the model Review and/or enforce uniqueness on the join-table to only allow a single user per movie. 您还希望在模型Review验证唯一性和/或在联接表上强制唯一性,以便每个电影仅允许一个用户。 It's up to you if you want to take this UQ constraint into the schema as well (DHH says 'Yes', I say 'the slathering of dumb persistance' is a 'No no'...) 是否还要将此UQ约束也纳入方案由您决定(DHH说“是”,我说“愚蠢的持久性刻薄”是“否”)。

User.reviews will give you the 'join records', ie along the lines of <Review user_id=x, movie_id=y> Certainly, you'd have a lot more columns on the join table pertaining to the review, such as :summary, :content etc. It's easy enough to access the movie from a review, ie Movie.find_by_id(User.reviews.last.movie_id).title User.reviews将为您提供“ User.reviews记录”,即沿着<Review user_id=x, movie_id=y>当然,您会在<Review user_id=x, movie_id=y>表上拥有与该评论有关的更多列,例如:summary, :content等。通过评论即可轻松访问电影,即Movie.find_by_id(User.reviews.last.movie_id).title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM