Active Record Queries and Chained Scopes Ordering

In Rails Fundamentals Active Record Querying exercise, we were asked to chain our scopes to get the requested results to appear in the view, and I chained my scopes as follows:

GuestbookEntry.recent.most_recent_first.limited

I thought, for purposes of resource management, that I’d first want to only pull from the database the most recent searches, then order all of those, then take the first 5. I figured ordering first, in the universe where lots of records that are not “recent” would be a waste of resources, and that calling limit anything but last would get the wrong results because limit pulls the first X records. My arrangement passed the tests.

To ensure that I understand what is happening (spoiler alert: it turns out I didn’t!), I rearranged the scopes:

GuestbookEntry.limited.recent.most_recent_first

but found that this rearrangement also passed the tests.

I posed this question to Upcase and @Tute_Costa responded, explaining that the order ultimately does not matter:

This is because when you chain scopes, ActiveRecord is not hitting the database, until you finish building the query you want and actually use the objects you are referencing. See for example to_a, which returns an array from the Relation: http://apidock.com/rails/ActiveRecord/Relation/to_a. As you see, it first calls load, which actually executes the database query: load (ActiveRecord::Relation) - APIdock.

Thoughts? Questions?

@Tute_Costa’s explanation sums it up.

As far as your original theory about how to speed up the transaction, remember that SQL is usually going to be faster than Ruby at doing things like ordering a set, filtering by criteria, or taking a specific slice (the kind of thing you’d do with limits and offsets). You only want to use methods from Array to do work that’s not possible or very difficult to do in a database query if the set of data you’re working with is anything larger than a handful of records.

One thing to remember is that if you’re applying multiple ordering scopes to a query (sorting more than once), is that in that case the order does matter. Cases like that are good to cover with a test so that you get exactly the sorting behavior you expect.