John Topley’s Weblog

Rails Tip #10: Listing Model Associations

You can use the built-in Rails console script to ask any model class for its associations:

Model.reflections.keys

—For example, let’s say we have a simple iTunes-like application in which a user can have one music library that contains many tracks:

class User < ActiveRecord::Base
  has_one :music_library
  .
  .
end
class MusicLibrary < ActiveRecord::Base
  belongs_to :user
  has_many :tracks
  .
  .
end
class Track < ActiveRecord::Base
  belongs_to :music_library
  .
  .
end

Now, firing up the Rails console and listing the associations produces the following output:

./script/console
>> User.reflections.keys
=> [:music_library]
>> MusicLibrary.reflections.keys
=> [:user, :tracks]
>> Track.reflections.keys
=> [:music_library]

Comments

There aren’t any comments on this post. Comments are closed.


Archives

  • Jan
  • Feb
  • Mar
  • Apr
  • May
  • Jun
  • Jul
  • Aug
  • Sep
  • Oct
  • Nov
  • Dec
  • 2017
  • 2016
  • 2015
  • 2014
  • 2013
  • 2012

More Archives


Sign In