ActiveRecord has many tricks up its sleeve.
One of the many is this seemingly simple association option called
which helps us to explicitly declare bi-directional associations.
Let’s have a look!
Seems almost redundant,
but it performs a very important function.
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
However if the option was not applied:
inverse_of to all
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:
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,