I have a query like this:
locations = Location.order('id ASC').limit(10)
which returns an array of 500 or so records – all the records in the table – i.e. the limit clause is being ignored.
Yet if I put a .all on the end:
locations = Location.order('id ASC').limit(10).all
it works and returns 10 records.
This code is being run in a rake task and I am using PostgreSQL if that makes any difference.
Why is it doing that? Surely the .all should not be required. What am I missing?
I think the behaviour depends on how you are handling the
locationsvariable after setting it. This is becauseLocation.order('id ASC').limit(10)isn’t querying records but is returning an object of typeActiveRecord::Relation. The query will only occur once you callall,first,each,map, etc. on that object.In my testing,
returns an array of 10 ids as you would expect. But
returns the total number of locations in the database, because it executes the SQL
which returns the full count of location rows (the limit is on the number of rows returned, not the count itself).
So if you are treating the result of
Location.order('id ASC').limit(10)as an array by iterating through it, you should get the same result as if you had addedall. If you are callingcount, you will not. Kind of unfortunate, as I think ideally they should behave the same and you shouldn’t have to know that you are dealing with anActiveRecord::Relationinstead of an array.