← All Articles

Now you can disable joins in Rails database associations

— Written by

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.

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!

Up next

Why the Design Process needs 'Wireframing' to succeed
Skcript https://blog.skcript.com/rails-disable-joins/ https://blog.skcript.com/svrmedia/heroes/rails-disable-joins.png

Get yourfree consulting today →