views:

186

answers:

2

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.

+12  A: 

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
Angela
+1  A: 

Sounds like a pretty silly thing to do run-time. What exactly are you trying to achieve? I assume that there are a simple and more commonly used solution to whatever your problem is.

If I had to, I'd use TheModel.read_inheritable_attribute(:reflections).

August Lilleaas
Uhhh... think Rake task. One that needs to know the associations.
JP
The models themselves knows about the associations. So I'm still not following you ; )
August Lilleaas