我正在使用一个 has many through 关联,如下所示:
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
我目前正在我的控制器中创建我的关联,如下所示:
rr = RecommendationRating.find_by_recommendation_id(recommendation_id)
rr ||= RecommendationRating.new(recommendation_id: recommendation_id)
rr.rating_id = rating_id
rr.save
或者,我可以为推荐分配评级,如下所示:
@recommendation = Recommendation.find(recommendation_id)
@rating = Rating.find(rating_id)
@recommendation.ratings << @rating
哪种方法是关联这些记录的正确方法,第一种方法有缺点吗?