Get rails associations from console

shajin picture shajin · May 4, 2011 · Viewed 15k times · Source

I have a model in my Rails application - User. I want all the associations to be listed in rails console, along with the type of association(1-1, 1-many).

Answer

Dylan Markow picture Dylan Markow · May 4, 2011
User.reflect_on_all_associations

This will return an array of associations similar to this:

#<ActiveRecord::Reflection::AssociationReflection:0x00000105575548 @macro=:has_many, @name=:posts, @options={}, @active_record=User(id: integer, login: string), @collection=false>

Sample code:

reflections = User.reflect_on_all_associations
reflections.each do |reflection|
  puts ":#{reflection.macro} => :#{reflection.name}"
end