13

Suppose I have an object Person, which has_many :foos and :bars.

Given an instance, p (p = Person.new), how do I programmatically determine what relationships are available?

i.e. p.some_method => ["foo", "bar"]

Paul Schreiber
  • 12,531
  • 4
  • 41
  • 63

1 Answers1

20

You can use Active Record Reflections (API here)

In your example:

p.class.reflect_on_all_associations(:has_many).collect {|a| a.name}
Ricardo Acras
  • 35,784
  • 16
  • 71
  • 112
  • In case anyone wants all associations like I did, just call `reflect_on_all_associations` without a parameter. – Sam Oct 10 '22 at 15:07