Rails has_many meta data
I have a model that declares multiple has_many
relationships. Is there meta data available in ActiveRelation such that I can loop through these has_many
relationships when working with this model in order to see how many has_many
relationships the model is inv开发者_JS百科olved in, and then access the contents of each from there?
Some pseudocode (will not run) if it helps clarify what my goal is:
MyModel.has_many_relationships.each do |relationship|
relationship.contents.each do |content|
# ...
end
end
Sure you can!
Try searching for "reflect_on_all_associations" in the Rails documentation!
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
精彩评论