2011-05-11 37 views
1

我有一個模型聲明多個has_many關係。在ActiveRelation中是否有元數據可供使用,以便我可以在使用此模型時循環訪問這些has_many關係,以便查看該模型涉及多少個has_many關係,然後從中訪問每個關係的內容?Rails has_many元數據

一些僞代碼(將無法運行),如果它有助於澄清我的目標是:

MyModel.has_many_relationships.each do |relationship| 
    relationship.contents.each do |content| 
     # ... 
    end 
end 

回答

2

當然可以!

嘗試在Rails文檔中搜索「reflect_on_all_associations」!

reflect_on_all_associations(macro = nil) 

Returns an array of AssociationReflection objects for all the associations in the class. If you only want to reflect on a certain association type, pass in the symbol (:has_many, :has_one, :belongs_to) as the first parameter. 

Example: 

    Account.reflect_on_all_associations    # returns an array of all associations 
    Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations 
+0

完美。謝謝Aditya! – inyourcorner 2011-05-11 11:51:49

+0

如果它最終成功,也許你也可以接受答案!乾杯! :) – 2011-05-11 11:52:47