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
end

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

The problem

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

User.joins(:employees).group("users.name").count("employees_users.id")

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.

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!