# Dynamically find associations of a model

**URL:** <https://www.ruby-forum.com/t/dynamically-find-associations-of-a-model/85018>\
**Category:** Rails\
**Created:** [February 9, 2007, 10:26am UTC](https://www.ruby-forum.com/t/dynamically-find-associations-of-a-model/85018 "2007-02-09T10:26:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Thushan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8c91f0/32.png) [@Thushan](https://www.ruby-forum.com/u/Thushan)\
**Post date:** [February 9, 2007, 10:26am UTC](https://www.ruby-forum.com/t/dynamically-find-associations-of-a-model/85018/1 "2007-02-09T10:26:15Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Thushan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8c91f0/32.png) [@Thushan](https://www.ruby-forum.com/u/Thushan)\
**Post date:** [February 9, 2007, 11:06am UTC](https://www.ruby-forum.com/t/dynamically-find-associations-of-a-model/85018/2 "2007-02-09T11:06:18Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Thushan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8c91f0/32.png) [@Thushan](https://www.ruby-forum.com/u/Thushan)\
**Post date:** [February 9, 2007, 6:02pm UTC](https://www.ruby-forum.com/t/dynamically-find-associations-of-a-model/85018/3 "2007-02-09T18:02:04Z")

</div>

Wow!  
Thanks Jean!
