RAILS: How to get has_many associations of a model

Pioz picture Pioz · May 21, 2010 · Viewed 7.7k times · Source

how I can get the has_many associations of a model?

For example if I have this class:

class A < ActiveRecord::Base
  has_many B
  has_many C
end

I would a method like this:

A.get_has_many

that return

[B,C]

Is it possible? Thanks!

Answer

nathanvda picture nathanvda · May 21, 2010

You should be using ActiveRecord reflections.

Then you can type something like this:

A.reflect_on_all_associations.map { |assoc| assoc.name}

which will return your array

[:B, :C]