Forum: Ruby on Rails Automatic loading of parent association weirdness?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Xavier (Guest)
on 2008-10-09 20:44
(Received via mailing list)
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:

<snip>

class Contact < ActiveRecord::Base
  has_many :assets
end

class Asset < ActiveRecord::Base
  belongs_to :contact
end

</snip>

And here follows a console/development.log transcript:

<snip>

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

</snip>

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
Frederick C. (Guest)
on 2008-10-09 20:47
(Received via mailing list)
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
Xavier (Guest)
on 2008-10-10 13:39
(Received via mailing list)
> 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? ;)

Thanks for the reality check anyway.

Cheers

Xavier
This topic is locked and can not be replied to.