Detecting associations in rails

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(
elsif =~ /_id/ && {|assoc|
assoc.foreign_key}.include?( then
column_output = @union.send(ModelA.associations[:foreign_key =>

<%= 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,

Is there any way to access that information?

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.


On Mar 3, 5:59 pm, [email protected] wrote:


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