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:
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:
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: to_a (ActiveRecord::Relation) - APIdock. As you see, it first calls load, which actually executes the database query: load (ActiveRecord::Relation) - APIdock.