dev | 2021-05-11T02:09:39+00:00
Now you can disable joins in Rails database associations
Hellonext Team / 2021-05-11T02:09:39+00:00
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: June 3rd, 2023 at 4:46:29 PM GMT+0
Hellonext is a user feedback tool and this article was written by many people at Hellonext. Hellonext helps prioritize product roadmap based on user-input.