我有一个声明多个has_many
关系的模型。 ActiveRelation中是否有可用的元数据,以便在使用此模型时可以循环使用这些has_many
关系,以查看模型所涉及的has_many
关系的数量,然后访问每个模型的内容从那里?
有些伪代码(不会运行),如果它有助于阐明我的目标:
MyModel.has_many_relationships.each do |relationship|
relationship.contents.each do |content|
# ...
end
end
答案 0 :(得分: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