On Sunday, 15 June 2014 23:47:31 UTC-5, Ruby-Forum.com User wrote:
>
> Hassan Schroeder wrote in post #1149759: 
> > On Sun, Jun 15, 2014 at 1:29 AM, Ronald Fischer <li...@ruby-forum.com 
> <javascript:>> 
> > wrote: 
> > (assume that ) box = Box.find(box_id) 
> > 
> > box.cards  #  has the cards you want *if* you need all the attributes 
> > 
> > box.cards.pluck(:id)  #  builds a query to fetch *only* the card ids 
>
> May I ask how this works (internally)? For pluck() to be applied, Ruby 
> has first to execute box.cards() to get an Array of the cards. Unless 
> the Card objects are implemented as proxies, which only fetch their data 
> from the database if one asks for it, I would at this point, at least 
> temporarily, have all the selected Card data in memory, isn't it? 
>
>
The short version: `box.cards` doesn't actually load the records until they 
are needed; that's why things like `box.cards.limit(10)` can work. 
`box.cards` returns a Relation, which *can* return records (if you call 
something on it that requires them, like `to_a` or `each`) but can also be 
used to construct SQL queries.

This is a bit tricky to see in the console, since typing `box.cards` there 
calls `inspect` on the Relation, which loads all the records.

For more detail, see the source.

--Matt Jones 

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/7204c876-da89-4027-b3c7-16a190900847%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to