Now you can disable joins in Rails database associations

You can now add an option to disable joins queries from happening in a has_many or has_one relationship. This is useful in a multi-database Rails architecture.

Karthik Kamalakannan

Karthik Kamalakannan

Now you can disable joins in Rails database associations

Rails is often touted for "works out of the box", however the same principle can be quite irksome when you need it to work for your use case. For a long time, it was impossible to declare associations when dealing with a multi-database structure. This is because associations can't join across databases.

Fortunately, Rails now offers the ability to disable joins when making associations. When this option is set, it Rails to make 2 or more queries rather than using joins.

Let's look at an example,

class Author
  has_many :articles
  has_many :votes, through: :articles, disable_joins: true
end

Now when we call author.votes, instead of a using a join to determine the votes accumulated by the author, Rails will do two separate queries.

SELECT "articles"."id" FROM "articles" WHERE "articles"."author_id":?  [["author_id", 1]]
SELECT "votes".* FROM "votes" WHERE "votes"."article_id" IN (?, ?, ?)  [["article_id", 1], ["article_id", 2], ["article_id", 3]]

You can also use the same option to has_one relationships as well!

class Author
  has_many :articles
  has_many :votes, through: :articles, disable_joins: true
 
  belongs_to :blog
  has_one :publisher, through: :blog, disable_joins: true
end

This is useful in multi-database architectures where associations can not be made across databases. This PR to the Rails codebase goes into further detail.

Prior to this implementation, you'd have to write individual methods that form these relationships instead,

class Author
  has_many :articles
  belongs_to :blog
 
  def votes
    Vote.where(article_id: self.articles.pluck(:id))
  end
 
  def publisher
    blog.publisher
  end
end

As you can see this new feature really cleans up the code!

Last updated: January 23rd, 2024 at 1:50:36 PM GMT+0

Subscribe

Get notified about new updates on Product Management, Building SaaS, and more.

Skcript 10th Anniversary

Consultants for ambitious businesses.

Copyright © 2024 Skcript Technologies Pvt. Ltd.