【问题标题】:How can I dynamically define a source for an ActiveRecord has_many relation?如何动态定义 ActiveRecord has_many 关系的源?
【发布时间】:2015-05-15 16:58:36
【问题描述】:

给定下面的 ActiveRecord 模型:

class Model < ActiveRecord::Base
  has_many :group_assignments
  has_many :product_assignments
  # Only one of the next two should appear, based on condition
  has_many :products, through: :product_assignments
  has_many :products, through: :group_assignments
end

希望根据以下条件定义最后一个 has_many...through 关系:如果模型有与之关联的任何产品分配,则产品来自产品分配。如果模型没有 product_assignments,则产品来自 group_assignments。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    不会发生。这些方法位于类级别,但您希望根据实例条件定义更多类级别关系。

    但是,您可以做的是保留 2 并使用将它们合并在一起的方法:

    has_many :pa_products, through: :product_assignments, source: :products
    has_many :ga_products, through: :group_assignments, source: :products
    
    def products
      (pa_products + ga.products).uniq
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2020-10-19
      • 1970-01-01
      相关资源
      最近更新 更多