在rails中添加具有不同关联类型的对象

时间:2014-03-23 18:43:03

标签: ruby-on-rails ruby-on-rails-4 model model-associations

以下是我的三个模型:许多用户可以通过关联模型获得许多产品(反之亦然)。

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

要向用户添加“中等”association.stngthngth产品,我通常会这样做:

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

我的问题是我如何做同样的事情并向用户添加产品但是具有“强”关联。强度初始化?

2 个答案:

答案 0 :(得分:1)

您可以通过

执行相同的操作
user.strong_associated_products << product

您可能需要以这种方式设置您的关系:

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 

结束

答案 1 :(得分:0)

添加@ sonnyhe2002的答案。我最终使用了回调,例如

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

然后

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