Re: After loading model, can it be again accessed without SQL...

Ball, Donald A Jr \(Library\)
Mon, 16 Apr 2007 16:35:41 -0000

> Quick question:
>
> 1 User -> many Accounts
>
> If I eager load the user with: my_user = User.find(:first, include =>
> [:accounts])
>
> How can I then use criteria to work with the "accounts"
> without making another query to the database?
>
> Iteration is one option, but it would be best to avoid it if
> say I wanted one of the accounts in the user by :name =>
> "Checking Account".

I don''t think you can. However, you might be able to do it another way.
If you know before the load which one account you want to look at, you
could do:

User.find(:first, :include=>[:accounts],
:conditions=>[''accounts.name ?'', ''Checking
Account''])

perhaps a bit less efficient than including the condition in the JOIN
itself, but it ought to work. Note that this will only work properly if
you''re only :including one relationship with many entities.

An alternate solution might be to include the condition in a manual
join:

User.find(:first, :joins=>''LEFT OUTER JOIN accounts on
accounts.user_id
= users.id AND accounts.name = ''Checking Account'')

then the account properties will appear on the user object, but I dunno
what will happen if the user and account objects share any property
names, nor do I know if the automatic sql type->ruby type mappings will
occur as usual.

- donald

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com