ActiveRecord "first" vs "last"

Hi,

According to Active Record Query Interface — Ruby on Rails Guides, “first” does not use “ORDER BY ID” to bring the first record. Whereas “last” does.

I find this inconsistent. I can also say that this is buggy on MySQL. “…limit 1” does not always bring the record with the minimum id. I can link you to the following that

verifies my statement: MySQL :: Does LIMIT 1 without ORDER BY ID bring the record with minimum ID?

Do you think that you can change “first” to be consistent with “last” (that does the order by id desc)?

BR

Panayotis

It is already done at master branch. https://github.com/rails/rails/commit/66b9e4c857b5987a52f0442ae382ee18dc3dd30a

This is already fixed on Rails 4.0

Just a thought,

how does this work with legacy tables that have no PK? What makes them possible now is that you can filter down with ‘where’ onto a single record and get .first out without triggering a fetch through ID. Perhaps implement an “any” finder method with same function as the old “first” ?

Borna

Yep, in Rails 4 the new #take method is the old #first:

    rails/finder_methods.rb at main · rails/rails · GitHub

Xavier

Thanks Xavier :slight_smile: