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?
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