Question

The following are my three models: many users can each have many products (and vice versa) through an associations model.

class Product < ActiveRecord::Base
  has_many :associations
  has_many :users, :through => :associations
end

class User < ActiveRecord::Base
  has_many :associations
  has_many :products, :through => :associations
  has_many :medium_associated_products, :class_name => "Product", :through => :associations, :source => :product, :conditions => ["associations.strength = ?", "medium"]
  has_many :strong_associated_products, :class_name => "Product", :through => :associations, :source => :product, :conditions => ["associations.strength = ?", "strong"]  
end

class Association < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
end

To add a "medium" association.strength product to the user, I usually do:

user.products << product  #associations.strength is by default "medium"

My question is how would I do the same thing and add a product to the user but with "strong" association.strength initalized?

Was it helpful?

Solution 2

Adding onto @sonnyhe2002's answer. I ended up using a callback such as

has_many :strong_associations, class_name: 'Association', condition: ["associations.strength = ?", "strong"], add_before: :set_the_strength

and then

def set_the_strength(obj)
   obj[:strength] = "strong"
end

OTHER TIPS

You can do the same with strong by

user.strong_associated_products << product

You may need to set to your relations this way:

class User < ActiveRecord::Base
  has_many :medium_associations, class_name: 'Association', condition: ["associations.strength = ?", "medium"]
  has_many :strong_associations, class_name: 'Association', condition: ["associations.strength = ?", "strong"]
  has_many :medium_associated_products, class_name: 'Product', through: :medium_associations, source: :product
  has_many :strong_associated_products, class_name: 'Product', through: :strong_associations, source: :product 

end

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top