The following blog post contains material either currently found or soon to be incorporated into my new book, "Easy Active Record for Rails Developers". Among many other topics, you'll learn about model generation, migrations, validations, associations, scopes, joins, includes, forms integration, nested forms, and model testing with RSpec and FactoryGirl. The book is now available, head over to this website's home page to learn more.


I find the Rails console so indispensable that a console session remains continuously open in a terminal. It offers a quick and convenient interface for testing Ruby syntax and experimenting with model queries.

As the project continues to evolve I’ll run the reload! command so the console is always apprised of the latest model changes. While in the console, when dealing with dozens of models and all of their various relations, it can be easy to forget a particular relationship name, and rather than dig through the project’s model definitions it’s easier to use a little known method called reflect_on_all_associations that will return an array of all model associations:

>> Location.reflect_on_all_associations
Location.reflect_on_all_associations
 => [#<ActiveRecord::Reflection::AssociationReflection:0x007fb39d082480 
 @macro=:belongs_to, @name=:state, 
 @scope=nil, @options={}, @active_record=Location(id: integer, 
 name: string, description: text, 
 created_at: datetime, updated_at: datetime, street: string, city: string, 
 zip: string, 
 latitude: decimal, longitude: decimal, state_id: integer, category_id: integer), 
 @plural_name="states", 
 @collection=false>, #<ActiveRecord::Reflection::AssociationReflection:0x007fb39d088d30 
 @macro=:belongs_to, 
 @name=:category, @scope=nil, @options={}, @active_record=Location(id: integer, 
 name: string, 
 description: text, created_at: datetime, updated_at: datetime, street: string, 
 city: string, 
 zip: string, latitude: decimal, longitude: decimal, state_id: integer, 
 category_id: integer), 
 @plural_name="categories", @collection=false>, 
 #<ActiveRecord::Reflection::AssociationReflection:0x007fb39b731238 
 @macro=:has_and_belongs_to_many, @name=:games, @scope=nil, 
 @options={}, @active_record=Location(id: integer, 
 name: string, description: text, created_at: datetime, updated_at: datetime, 
 street: string, city: string, 
 zip: string, latitude: decimal, longitude: decimal, state_id: integer, 
 category_id: integer), 
 @plural_name="games", @collection=true>] 

Of course, this can be kind of a mess to sort through when you’re dealing with even a few associations, but because the return value is an array you can iterate over it easily enough:

>> Location.reflect_on_all_associations.each do |a|
>>   puts "#{a.macro} => #{a.name}"
>> ?> end
belongs_to => state
belongs_to => category
has_and_belongs_to_many => games

Like what you read? There’s plenty more where this came from in my new book, “Easy Active Record for Rails Developers”!

Comments