0

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)

Thanks

4

1 に答える 1

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たり、結合テーブルに一意性を適用して、映画ごとに1人のユーザーのみを許可したりすることもできます。このUQ制約をスキーマにも取り入れたいかどうかはあなた次第です(DHHは「はい」と言います、私は「ダムの永続性のスラッシング」は「いいえいいえ」と言います...)

User.reviews「結合レコード」が表示されます。つまり、次の行に沿って<Review user_id=x, movie_id=y> 表示されます。確かに、レビューに関連する結合テーブルには、などの列がたくさんあります:summary, :content。レビューから映画にアクセスするのは簡単です。Movie.find_by_id(User.reviews.last.movie_id).title

于 2012-06-20T16:21:17.250 に答える