Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the associations for an ActiveRecord class at run-time?

I would like to find the assocations of an ActiveRecord class at runtime...

Let's assume I have the following:

class Person < ActiveRecord::Base
  has_many :chairs
  has_many :pens
end

class Chair < ActiveRecord::Base
  belongs_to :person
end

class Pen < ActiveRecord::Base
  belongs_to :person
end

How can I find out at runtime that Person "has many" Chairs and Pens, and vice versa? I'm looking for a method that would return an array of strings (if such a method exists). i.e.

Person.has_many_assocations 

would return:

["chairs", "pens"] 

and

Pen.belongs_to_associations

would return:

["person"]

Am I missing a method like this that exists??

Thanks for your help.

like image 607
JP Richardson Avatar asked Mar 13 '09 21:03

JP Richardson


1 Answers

I think the ActiveRecord::Reflection class may be what you're looking for. From the documentation:

  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
like image 97
Angela Avatar answered Oct 15 '22 03:10

Angela