RAILS: How to get has_many associations of a model
Asked Answered
S

3

26

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!

Sapota answered 21/5, 2010 at 8:36 Comment(0)
I
46

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]
Ina answered 21/5, 2010 at 10:33 Comment(2)
To get only has_many associations, it is possible to pass a parameter: A.reflect_on_all_associations(:has_many).map(&:name) #=> [:B, :C]Wantage
is there a way to reflect (i.e. traverse) on an instance variable, where the associations have been eagerly loaded?Alcazar
A
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!

Anaglyph answered 21/5, 2010 at 9:5 Comment(0)
S
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
Sapota answered 21/5, 2010 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.