ActiveRecord has many tricks up its sleeve.
One of the many is this seemingly simple association option called inverse_of
,
which helps us to explicitly declare bi-directional associations.
Let’s have a look!
Seems almost redundant,
but it performs a very important function.
When inverse_of
is declared,
one can update related models without explicitly writing update statements.
As you can see,
without actually updating the name of the author,
inverse_of
was able to relate the models.
Another useful element is that inverse_of
stores a copy of the relation in the ActiveRecord query.
So when you call upon the association,
it does not need to load it from the database.
As you can see, the inverse_of
filter is now applied to the belongs_to
relation.
However if the option was not applied:
Before
Fortunately,
Rails adds inverse_of
to all belongs_to
associations.
Unfortunately,
it does not do so when a scope is added to the association.
Let’s look at an example:
Now let’s perform the queries:
After
Thanks to changes in Rails 7, automatic inverse_of detection for associations with scopes now works!.
Let’s look at the same example again:
As you can see, no database query was made. This option is not enabled by default in Rails 7. To enable it please set this configuration option,