It took me several years of working with Rails to understand this nuance, and I believe it is poorly documented in the AR guide. "reading the source" may be a good idea for some, but remember the Rails source isn't easy for everyone to read (although a good idea!).
Since it is so important to how AR works, I think this facet of AR should be documented better in the AR guide (specifically, that the AR methods return ActiveRelation objects which don't actually fetch anything until you want to look at them). It's a brilliant implementation pattern, but counter-intuitive to newbies. -Jason On Jun 16, 2014, at 3:54 PM, Matt Jones <[email protected]> wrote: > > > 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 <[email protected]> > > 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 [email protected]. > To post to this group, send email to [email protected]. > 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. -- 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 [email protected]. To post to this group, send email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/A5E720F1-92CF-47F3-A22C-8A38E91807A3%40datatravels.com. For more options, visit https://groups.google.com/d/optout.

