# Detecting associations in rails

**URL:** <https://www.ruby-forum.com/t/detecting-associations-in-rails/87575>\
**Category:** Ruby\
**Created:** [March 4, 2007, 2:36am UTC](https://www.ruby-forum.com/t/detecting-associations-in-rails/87575 "2007-03-04T02:36:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zig](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/bbe5ce/32.png) [@zig](https://www.ruby-forum.com/u/zig)\
**Post date:** [March 4, 2007, 2:36am UTC](https://www.ruby-forum.com/t/detecting-associations-in-rails/87575/1 "2007-03-04T02:36:17Z")

</div>

In Rails, is there a way to list at runtime the associations (has\_one,  
belongs\_to, etc) made for an ActiveRecord::Base model?

I would like to make my views be a little smarter about these  
associations. Currently, the scaffolding iterates through all  
content\_columns, which excludes the columns used for the associations,  
since they end in \_id. Iterating through all columns, instead of just  
content\_columns, is not much better, because I don’t want to see the  
foreign\_key either. What I’d really like is something along the lines  
of this:

\<% for column in ModelA.columns %\>  
\<%  
if ModelA.content\_columns.include?(column) then  
column\_output = @union.send(column.name)  
elsif column.name =~ /\_id/ && ModelA.associations.map {|assoc|  
assoc.foreign\_key}.include?(column.name) then  
column\_output = @union.send(ModelA.associations[:foreign\_key =\>  
column\_name])  
end  
%\>

**\<%= column.human\_name %\>:** \<%=h column\_output %\>

\<% end %\>

OK, my logic above isn’t perfect, needs some cleaning up, but  
whatever. The point is, I need a method like associations, which can  
tell me what associations a model has, what their foreign keys are,  
etc.

Is there any way to access that information?

---

<div class="post-metadata">

**Author:** ![zig](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/bbe5ce/32.png) [@zig](https://www.ruby-forum.com/u/zig)\
**Post date:** [March 4, 2007, 3:00am UTC](https://www.ruby-forum.com/t/detecting-associations-in-rails/87575/2 "2007-03-04T03:00:18Z")

</div>

Hi –

On Sun, 4 Mar 2007, zig wrote:

> Is there any way to access that information?

ActiveRecord::Base.reflect\_on\_all\_associations can probably give you  
what you need.

David

---

<div class="post-metadata">

**Author:** ![zig](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/bbe5ce/32.png) [@zig](https://www.ruby-forum.com/u/zig)\
**Post date:** [March 4, 2007, 11:10pm UTC](https://www.ruby-forum.com/t/detecting-associations-in-rails/87575/3 "2007-03-04T23:10:56Z")

</div>

On Mar 3, 5:59 pm, removed\_email\_address@domain.invalid wrote:

> David

Yes, that’s exactly what I was looking for. Thanks for showing me  
where it was!
