Loading ActiveRecord associations by hand

Hello,

I'm having this frustrating problem with AR. I want to load AR
associations by hand. I have the following situation:
* 2 models: child and parent
* parent has has_one association to child
* I have loaded set of parent objects (without children)

Now I want to load parent objects with childrens with only one sql
select.

So I load child objects according to parent ids. Did it with one
select, so that's fine. But then the troubles begin. Now I want to
dynamically associate (or fill association) every parent object with
corresponding object. So I set it with:
parent.child = child

But that also saves the object, which I do not want. I've also tried
with "parent.build_child( child.attributes", but this is even worse,
as it also destroys existing object before setting it..

So please... can anyone help me, how to load associations by hand?

Many thanks!

Uros

Hello,

I'm having this frustrating problem with AR. I want to load AR
associations by hand. I have the following situation:
* 2 models: child and parent
* parent has has_one association to child
* I have loaded set of parent objects (without children)

Now I want to load parent objects with childrens with only one sql
select.

So I load child objects according to parent ids. Did it with one
select, so that's fine. But then the troubles begin. Now I want to
dynamically associate (or fill association) every parent object with
corresponding object. So I set it with:
parent.child = child

This is basically how edge rails handles eager loading, the relevant
bit of code is at http://dev.rubyonrails.org/browser/trunk/activerecord/lib/active_record/association_preload.rb
(look at the set_association_single_records/
set_association_collection_records methods in particular, don't forget
to call loaded on the association too)

Fred

Thanks for the tip Fred, it worked!

Instead of "parent.child = child"
I've used: "parent.set_child_target( child )"

Work like a charm (so far)!