Active Record Ruby on Rails

Ruby on Rails / ActiveRecord: tables naming in a self join

Ruby on Rails / ActiveRecord: tables naming in a self join January 19, 20183 Comments

Usually, you don’t think about tables naming because it’s obvious. However, there is a case when you might stop for a second. I’m talking about a self-join instruction. Let’s consider following example: there is a User model and it has manager_id column. This column points to the same table so basically User model operates on both managers and users.

User model

Our model looks like this:

class User < ActiveRecord::Base
  belongs_to :manager, class_name: "Person", foreign_key: :manager_id
  has_many :employees, class_name: "Person", foreign_key: :manager_id

The problem

We may want to fetch managers and show employees count for each manager. We can do it using the following query:


As you may already noticed we used employees_users name. Since we do join, we have two tables even if we join the same table.

The pattern

There is a pattern that you can use when doing such operations. Just combine plural version of association name and model name. That’s it.

Photo by Flash Bros from Pexels

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.


Leave a Reply

Your email address will not be published. Required fields are marked *