Pioz
Pioz

Reputation: 6321

RAILS: How to get has_many associations of a model

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!

Upvotes: 26

Views: 9306

Answers (3)

nathanvda
nathanvda

Reputation: 50057

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]

Upvotes: 46

Pioz
Pioz

Reputation: 6321

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

Upvotes: 0

azaupa
azaupa

Reputation: 31

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!

Upvotes: 3

Related Questions