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).

2 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.

Leave a Reply