Forum: Ruby on Rails Dynamically find associations of a model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Thushan (Guest)
on 2007-02-09 11:26
(Received via mailing list)
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
Jean-François (Guest)
on 2007-02-09 12:06
(Received via mailing list)
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.
Thushan (Guest)
on 2007-02-09 19:02
(Received via mailing list)
Wow!
Thanks Jean!
This topic is locked and can not be replied to.