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

时间:2015-05-15 16:58:36

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

鉴于下面的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 ...通过关系:如果模型具有与之关联的任何产品分配,则产品来自产品分配。如果模型没有product_assignments,则产品来自group_assignments。

1 个答案:

答案 0 :(得分: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