Rails has_many元数据

时间:2011-05-11 11:46:14

标签: ruby-on-rails activerecord

我有一个声明多个has_many关系的模型。 ActiveRelation中是否有可用的元数据,以便在使用此模型时可以循环使用这些has_many关系,以查看模型所涉及的has_many关系的数量,然后访问每个模型的内容从那里?

有些伪代码(不会运行),如果它有助于阐明我的目标:

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

1 个答案:

答案 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