【问题标题】:Adding objects with different association types in rails在rails中添加具有不同关联类型的对象
【发布时间】: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


    【解决方案1】:

    你可以用 strong by 做同样的事情

    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 
    

    结束

    【讨论】:

    • 我刚刚意识到这似乎不起作用,因为“associations.strength”没有设置为“strong”
    【解决方案2】:

    添加到@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
    

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2013-11-13
      • 1970-01-01
      • 2016-05-25
      • 2015-10-24
      • 2023-01-31
      • 2015-06-22
      • 2018-07-07
      • 2017-01-25
      相关资源
      最近更新 更多