Skip to content
This repository

ActiveRecord::Relation#last ignores limit #371

Closed
dmarkow opened this Issue · 3 comments

3 participants

Dylan Markow José Valim Nick Howard
Dylan Markow
dmarkow commented

The limit option is ignored when calling #last on an ActiveRecord::Relation object:

Item.where("id <= 3").order(:id).limit(2)
# returns records #1 and #2
Item.where("id <= 3").order(:id).limit(2).last
# returns record #3, not record #2 as expected, since the limit is overridden by last
Item.where("id <= 3").order(:id).limit(2).all.last
# executing the query uses Array#last instead of ActiveRecord::Relation#last, and returns #2 as expected
Nick Howard

What would you expect it to return if there were less than the limit number of objects?

The reason limit is ignored is because find_last resets it to limit(1) after reversing the order. Have you tried using offset to get the behavior you want?

Nick Howard baroquebobcat referenced this issue from a commit in baroquebobcat/rails
Nick Howard Fix for #371
if a query contains a limit or an offset, ActiveRecord::FinderMethods#find_last had inconsistent behavior.

If the records were loaded, it returned the last record in the cached list.
If they were not, it reversed the order of the query and changed the limit to one.
If the earlier limit was less than the total matching the query in the db,
it would return a different record than if the records had been cached.

This commit changes find_last so that it loads the records when getting the
last record on a query containing a limit or an offset, which makes the behavior consistent.
95b2590
Nick Howard

I put together a patch #451

José Valim
Owner

Closing this in favor of the pull request.

José Valim josevalim closed this
Jon Leighton jonleighton referenced this issue from a commit
Nick Howard Fix for #371
if a query contains a limit or an offset, ActiveRecord::FinderMethods#find_last had inconsistent behavior.

If the records were loaded, it returned the last record in the cached list.
If they were not, it reversed the order of the query and changed the limit to one.
If the earlier limit was less than the total matching the query in the db,
it would return a different record than if the records had been cached.

This commit changes find_last so that it loads the records when getting the
last record on a query containing a limit or an offset, which makes the behavior consistent.
92c1076
Vijay Dev vijaydev referenced this issue from a commit
Commit has since been removed from the repository and is no longer available.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.