I am using a has many through association as follows:
class Rating < ActiveRecord::Base
has_many :recommendation_ratings, :dependent => :destroy
has_many :recommendations, :through => :recommendation_ratings
end
class Recommendation < ActiveRecord::Base
has_many :recommendation_ratings, :dependent => :destroy
has_many :ratings, :through => :recommendation_ratings
end
class RecommendationRating < ActiveRecord::Base
validates :recommendation_id, presence: true
validates :rating_id, presence: true
belongs_to :recommendation
belongs_to :rating
end
I am currently creating my associations in my controller as follows:
rr = RecommendationRating.find_by_recommendation_id(recommendation_id)
rr ||= RecommendationRating.new(recommendation_id: recommendation_id)
rr.rating_id = rating_id
rr.save
Alternatively, I could assign ratings to recommendations like so:
@recommendation = Recommendation.find(recommendation_id)
@rating = Rating.find(rating_id)
@recommendation.ratings << @rating
Which is the correct method to associate these records, and is there a downside to doing it the first way?
That depends on what you need.
The first one updates a
recommendation_ratingrecord if it already exists and enables you to run callbacks and validation after callingsaveThe second one creates a rating everytime you call
<<and it creates the record directly on the database so no validation and callback is triggered.