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
I believe this is the approach you should be taking
You would also want to validate uniqueness in the model
Reviewand/or enforce uniqueness on the join-table to only allow a single user per movie. 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’…)User.reviewswill give you the ‘join records’, i.e. 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, :contentetc. It’s easy enough to access the movie from a review, i.e.Movie.find_by_id(User.reviews.last.movie_id).title