2011-05-11 35 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