Tables naming in a Rails self join
published on NOV 1, 2018
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.
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
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.
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.