In our previous post, we’ve shown how to use the disable_joins option for has_many: :through association. In this post, we would like to show, how that works for the has_one: :through association as well.

Let’s consider the use case where:

• Users can create multiple posts.
• Anyone looking at the post can add a comment - crowd-sourced comments.

In this case, we can store the crowd-sourced comments in a separate database, as comments can grow quickly and may need a different kind of data management approach.

The database.yml can be like below:

The models would look like below:

#### Before

In Rails 6, to fetch the latest comment for a user, we need to add a custom method, as associations can’t join across databases.

Here, we are fetching the most recent comment created on the posts created by the user. As comments are in different a database, need to pluck the post ids.

For all such associations across different databases, we will have to add custom methods as above.

#### After

Rails 7 has added an option in has_one :through association to make it easier to have multiple databases joining. We can use the has_one :through association with the newly added disable_joins: true option like below.

We do need to add one association in the User model for the latest_post in this case.

If we try to load the latest_comment association now, it fires 2 separate queries to load the post ids, and the latest comment with those post ids.

This allows us to eager load the latest comment.