Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAILS: How to get has_many associations of a model

Tags:

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!

like image 409
Pioz Avatar asked May 21 '10 08:05

Pioz


People also ask

How would you choose between Belongs_to and Has_one?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


2 Answers

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] 
like image 117
nathanvda Avatar answered Sep 23 '22 18:09

nathanvda


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!

like image 26
azaupa Avatar answered Sep 21 '22 18:09

azaupa