[Ruby on Rails (RoR)] Cross-cluster associations to Rails 7

Cross-cluster Associations

Most recently, Github Ruby team extracted internal functionality to disable joining queries when an association crossed multiple databases. Prior to our work in this area, Rails had no support for handling associations that spanned across clusters; teams had to write SQL to achieve this.

The overall implementation is relatively small. To accomplish disabling joins, we added an option to has_many :through associations called disable_joins. When set to true for an association, Rails will generate separate queries for each database rather than a join query.

Now applications can add the following to their associations to make sure Rails generates two or more queries instead of joins:

1
2
3
4
class Dog < AnimalsRecord
has_many: treats, through: :humans, disable_joins: true
has_many :humans
end

And that’s all that’s needed to disable generating joins for associations that cross database servers!

Now, calls to dog.treats will generate the following SQL:

1
2
SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ?  [["dog_id", 1]]
SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]]

References

[1] Adding support for cross-cluster associations to Rails 7 | The GitHub Blog - https://github.blog/2021-07-12-adding-support-cross-cluster-associations-rails-7/

[2] Ruby on Rails 7.0 Release Notes — Ruby on Rails Guides - https://edgeguides.rubyonrails.org/7_0_release_notes.html

[3] Ruby on Rails | A web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern. - https://rubyonrails.org/