Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

Creating associations using has_many through with additional attribute


I have the 3 models:

class Product < ActiveRecord::Base
  has_many :product_recommendations, :dependent => :destroy
  has_many :recommendations, :through => :product_recommendations
end

class Recommendation < ActiveRecord::Base
  has_many :product_recommendations, :dependent => :destroy
  has_many :products, :through => :product_recommendations
end

class ProductRecommendation < ActiveRecord::Base
  belongs_to :recommendation
  belongs_to :product
end

I also have a method which created a new recommendation(s):

def self.get_recommendation(product, rating_set)
    r = Recommendation.create
           r.title            =  @title
           r.description      =  @description
           r.cover_img        =  @image_url
           r.curr_price       =  @curr_item_price
           r.save! 
end

I am passing in the product object and rating_set attribute when I call the method.

How do I create an product_recommendation association with the 1)The product object. 2) The newly created recommendation object. 3) An additional attribute(rating_set) which belongs to the ProductRecommendation join table.

I tried the following with no luck:

product.create_product_recommendations( {:rating_set => rating_set}, {:recommendation => r} ) 
product.recommendations.create( :rating_set => rating_set, :recommendation => r )

Solution

  • I solved this by creating the record on the join table as so:

    pr = ProductRecommendation.new(:rating_set => rating_set.id, :recommendation_id => r.id, :product_id => product.id)
    pr.save!