I have the following models, with their relevant associations:
class User < ActiveRecord::Base
has_many :reviews
has_many :ratings
end
class Product < ActiveRecord::Base
has_many :reviews
has_many :ratings
end
class Review < ActiveRecord::Base
belongs_to :product
belongs_to :user
end
class Rating < ActiveRecord::Base
belongs_to :product
belongs_to :user
end
Given a specific Rating, I need to get to the corresponding Review (if a review exists).
I need to keep ratings and reviews loosely coupled. (I do not want to set up my model so that a Review belongs_to a Rating)
How should I set up a rating's association to reviews?
Once I’m working with a specific rating in a view, I can call @rating.product.reviews.where(:user_id => @rating.user.id).first, but I’d like it to be cleaner/more efficient if possible.
Any ideas?
Thanks.
Try using :conditions like so:
If that doesn’t work, do this instead (very much like what @RobinBrouwer answer):