47
class Article < ActiveRecord::Base
  has_many :comments
  belongs_to :category
end

Is there a class method for Article with which I can retrieve a list of associations? I know by looking at the model's code that Article is associated to Comment and Category. But is there a method to get these associations programmatically?

primary0
  • 1,180
  • 1
  • 10
  • 21

1 Answers1

78

You want ActiveRecord::Reflection::ClassMethods#reflect_on_all_associations

So it would be:

 Article.reflect_on_all_associations

And you can pass in an optional parameter to narrow the search down, so:

 Article.reflect_on_all_associations(:has_many)

 Article.reflect_on_all_associations(:belongs_to)

Keep in mind that if you want the list of all the names of the models you can do something like:

Article.reflect_on_all_associations(:belongs_to).map(&:name)

This will return a list of all the model names that belong to Article.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111