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