如何动态定义 ActiveRecord has_many 关系的源?

How can I dynamically define a source for an ActiveRecord has_many relation?

给定以下 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.

不会发生。这些方法处于 class 级别,但是您希望根据实例的条件来决定定义更多 class 级别的关系。

但是您可以做的是保留 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