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

Thorsten
Mon, 16 Apr 2007 21:44:35 -0000

from what i know that''s no problem at all ?!? that''s the whole
point
of eager loading....

@user = User.find(:first, include => [:accounts])

@user.accounts.find(blablaba-)
@user.accounts.each do { |account| blablabla }
@user.accounts.count

these and more will workwithout re-querying the database. basically
any AR method you use on @user.accounts won''t hit the database, except
for updating/adding/removing an account, of course.

On 16 Apr., 18:35, "Ball, Donald A Jr \(Library\)"
<donald.b...-GjtI+QwuxAR68HQyEA6aog@public.gmane.org>
wrote:
> > 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-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org