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:
Without :inverse_of m and f.man would be different instances of the same object (f.man being pulled from the database again).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
Can you explain how inverse_of is in any way necessary? The relationships are already described via has_one and belongs_to.
Currently all relationship are one-way. A practical explanation would be that if you have:
You will end up eager-loading both riders and horses, that’s great. So
@riders.first.horsewill not run any extra SQL queries. However,@riders.first.horse.riderwill run an additional query to fetch the horse’s rider. Because Rails won’t know that they should be the same object. The comprehensive solution would be an identity map, but this commit was a start in the right direction.