Custom Named Belongs_to Associations in Rails with foreign key constraints

/ tutorials / ruby on rails ,  activerecord

Associations are great in Rails. There is a ton of functionality baked right in. One such feature is the ability to change the name of association columns.

First, lets talk through some setup data. We are working with two models: Journal and User. And their respective association:

  • A User has_many Journals
  • A Journal belongs_to a User

Given this information you might come up with something like

rails generate AddUserToJournal user:references

# app/models/journal.rb
class Journal < ActiveRecord::Base
  belongs_to :user

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :journals

user =
Journal.create(user: user)

Who is the creator of the Journal?

The previous setup works as you would expect, but what if you wanted to better describe who created a Journal without changing the classname for User? You might want a column named creator that stores the user who created the journal. This would allow for more readable association language for future developers.

Rails has some built in support to achieve just this using some additional arguments within the belongs_to method. Note: this requires no changes to the User model.

rails generate AddCreatorToJournal creator_id:integer # Can't use references since we are now aliasing to creator

# app/models/journal.rb
class Journal < ActiveRecord::Base
  belongs_to :creator, class_name: :User

user =
Journal.create(creator: user) # Check this out! Rails magic allows us to pass in a user as a creator

Our model now responds to the column name creator the same way it would to a standard user reference.

One step further

You can improve on this approach by adding an index and foreign key to the creator_id column in the migration. This ensures referential integrity as well as speeding up any queries based on creator_id.

# What the migration might look like
class AddCreatorToJournal < ActiveRecord::Migration
  def change

    # Notice how the index is for :creator but references users
    add_reference :journals, :creator, references: :users, index: true

    # Just like the belongs_to contained class_name: :User, the foreign key
    # also needs a specific custom column name as :creator_id
    add_foreign_key :journals, :users, column: :creator_id

# app/models/journal.rb
class Journal < ActiveRecord::Base
  # Sets the specific name of the foreign key to the creator_id like in the
  # migration above
  belongs_to :creator, class_name: :User, foreign_key: :creator_id

Now you have a custom named column, that is constrained based on a foreign key , and indexed for faster querying. There are plenty of other tricks with associations that can also be found on Rails Guides.

Join the conversation

comments powered by Disqus