Better in-memory associations with :inverse_of

Today Rails gained a very interesting commit from h-lame. It’s the first major step towards making associations aware of their parent model while still in-memory. A few days ago I started this discussion which revealed to me that it had been a long time coming, just no one bothered.

Well, finally someone did. I would like to thank h-lame for making this commit happen. Here’s the excerpt from the commit message.

You can now add an :inverse_of option to has_one, has_many and belongs_to associations. This is best described with an example:

      class Man < ActiveRecord::Base
        has_one :face, :inverse_of => :man
      end

      class Face < ActiveRecord::Base
        belongs_to :man, :inverse_of => :face
      end

      m = Man.first
      f = m.face
Without :inverse_of m and f.man would be different instances of the same object (f.man being pulled from the database again).

5 responses to “Better in-memory associations with :inverse_of”

  1. Clay Shentrup

    Can you explain how inverse_of is in any way necessary? The relationships are already described via has_one and belongs_to.

  2. Michael Durrant

    Clay you are correct that “The relationships are already described via has_one and belongs_to.”

    I believe that what is actually being addressed here is basically a performance issue, i.e. the current system works ok but could be more efficient. In this case it’s about memory and the second instantiation of the object being unnecessary and wastful when the first could be reused.

  3. Sathya Sekaran

    It’s not just a performance issue. Say if you’re saving a model and you want the associated model to be aware of pending changes to the parent model. That’s not easily possible without this.

Leave a Reply