Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of related models in rails

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"]

like image 300
Paul Schreiber Avatar asked Sep 10 '10 22:09

Paul Schreiber


1 Answers

You can use Active Record Reflections (API here)

In your example:

p.class.reflect_on_all_associations(:has_many).collect {|a| a.name}
like image 190
Ricardo Acras Avatar answered Oct 12 '22 23:10

Ricardo Acras