2015-05-15 21 views
1

下面給出的ActiveRecord的模式:如何動態定義ActiveRecord has_many關係的源代碼?

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

不會發生。這些方法處於類級別,但是您希望根據實例的條件來決定定義更多類級關係。

什麼但是你可以做的就是保持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