Automatic loading of parent association weirdness?

Hi there,

I’m experiencing some weird behavior with automatic loading of parent
associations in ActiveRecord using Rails 2.1.

Let’s take this simple model:

class Contact < ActiveRecord::Base
has_many :assets
end

class Asset < ActiveRecord::Base
belongs_to :contact
end

And here follows a console/development.log transcript:

a = Asset.find(:first, :include => {:contact => :assets})

Asset Load (0.000399) SELECT * FROM assets LIMIT 1
Contact Load (0.000300) SELECT * FROM contacts WHERE
(contacts.id IN (‘1’))
Asset Load (0.009318) SELECT assets.* FROM assets WHERE
(assets.contact_id IN (1))

(looks alright to me)

c = a.contact

(This yields no query, as expected)

f = c.assets.first

(This yields no query, as expected)

f.contact

Contact Load (0.000408) SELECT * FROM contacts WHERE
(contacts.id = 1)

Now why isn’t this asset’s contact record already associated to the
existing contact instance?

I’ve been using Rails for years and it’s the very first time I notice
such a behavior. It has always occured to me that, when invoking
parent.association, all records in association had their parent
already set to an existing instance, without having to hit the
database.

Any idea on this?

Greets,

Xavier

On 9 Oct 2008, at 17:36, Xavier wrote:

parent.association, all records in association had their parent
already set to an existing instance, without having to hit the
database.

It’s always been like this (:include is a red herring here, even
without eager loading in the picture, if you do

x = parent.child #=> 1 query, loads child
x.parent #=> 1 query, loads parent again)

This is far from ideal but it’s nothing new

Fred

This is far from ideal but it’s nothing new

Wow, I am so totally baffled.

I’m still wondering how I managed to never notice this, I’ve always
taken the presence of the parent for granted when loading members of
an association… probably because this lack doesn’t make a whole lot
of sense, does it? :wink:

Thanks for the reality check anyway.

Cheers

Xavier