Dynamically find associations of a model


#1

How can I dynamically find associations of a model?

eg.
class TravelService < ActiveRecord::Base
belongs_to :main_service
belongs_to :travel_grade
belongs_to :travel_type
end

tempClass = “TravelService”.constantize

Now, I want to find associations of tempClass.

Expected value:
tempClass = [MainService, TravelGrade, TravelType]

Thanks in advance for any help.

Thushan


#2

Hi Thushan,

Now, I want to find associations of tempClass.

Expected value:
tempClass = [MainService, TravelGrade, TravelType]

use :

tempClass.reflect_on_all_associations

or

tempClass.reflect_on_all_associations(:belongs_to)

… if you only want the belongs_to associations.

To collect the name of belongs_to associations, you can then
write :

tempClass.reflect_on_all_associations(:belongs_to).map(&:name)

it will not return an array of constants, since an association name
can just be a name, not necesseraly related to a class name.

– Jean-François.


À la renverse.


#3

Wow!
Thanks Jean!