Search code examples
ruby-on-railsactiverecordhas-manybelongs-tomodel-associations

How do you get the names of models that have MyObject has_many of?


Using Ruby (1.8.7) and Rails (2.3.8)

doing myObject.attributes gives you a hash of attribute to value.

lets say I have the scenario:

class MyObject
    has_many :other_objects

class OtherObject
    belongs_to :my_object

There should be a way to get the names of the associations tied to an object, right?

Even if there isn't be default, I'd be interested in help with a .associations method, similar to the .attributes -- except, return an array instead of a hash.


Solution

  • reflect_on_all_associations should do it.

    Example:

    MyObject.reflect_on_all_associations.map{|a| a.name.to_s} #=> ["other_objects"]