Blog post -

The (unknown?) inverse_of


Sometimes when working with Rails objects with relationships in memory, strange things can happen. You can edit the attribute of some object and when accessing it using a relationship, the changes will be gone. It has to do with in-memory objects and how ActiveRecord handles them. But there is a way to make sure you always work with the same object.

inverse_of is a Rails relationship option that will optimize object loading and can be really helpful when you're working with object in memory a lot. It's not very well documented, so I thought I'd write a small blog post about it.

The setup:

Setup gist

If I were to open up a console and add a Post with two Comments, I could then do this:

Console gist

The last few lines does seem weird, doesn't it? I was banging my head quite a bit after discovering this. But here's inverse_of to the rescue! Please note the pluralization of comments, it maps to how the inversed relationship will be used.

Gist

Using inverse_of will trigger ActiveRecord to optimize object handling. In other words, it will use the same in-memory object when it's the same object and accessing it the way the inverse_of relationship has been configued.

Inverse of gist

It has a few limitations and you can read some more about it in the Ruby on Rails documentation.

Categories

  • ruby on rails