25

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!

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Pioz
  • 6,051
  • 4
  • 48
  • 67

3 Answers3

44

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]
nathanvda
  • 49,707
  • 13
  • 117
  • 139
  • 26
    To get only `has_many` associations, it is possible to pass a parameter: `A.reflect_on_all_associations(:has_many).map(&:name) #=> [:B, :C]` – Tatjana N. May 21 '10 at 11:08
  • is there a way to reflect (i.e. traverse) on an *instance* variable, where the associations have been eagerly loaded? – Mark Richman Jul 03 '12 at 20:11
3

For Example you could try :

aux=Array.new
Page.reflections.each { |key, value| aux << key if value.instance_of?(ActiveRecord::Reflection::AssociationReflection) }

Hi Pioz , Have a Nice Day!

azaupa
  • 31
  • 1
0

Found the solutions:

def self.get_macros(macro)
  res = Array.new
  self.reflections.each do |k,v|
    res << k if v.macro == macro.to_sym
  end
  return res
end
Pioz
  • 6,051
  • 4
  • 48
  • 67