【发布时间】:2014-03-23 18:43:02
【问题描述】:
以下是我的三个模型:许多用户可以通过关联模型拥有许多产品(反之亦然)。
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
为了给用户添加一个“中等”的关联.强度产品,我通常会这样做:
user.products << product #associations.strength is by default "medium"
我的问题是我将如何做同样的事情并向用户添加产品但“强”关联。强度初始化?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 model model-associations