rails/rails — pull request #12153 by danmcclain (2013-09-06 17:58:41+00:00)
Title: Removes order by primary key from ActiveRecord::FinderMethods#find_first

The fact that ActiveRecord::FinderMethods#find_first implicitly applies a sort
order by the primary key of the table will work against the query intended by
the developer. An example of where the order by primary key works against the
developer happens when using the `rank()` window function in PostgreSQL. Take the following query

```sql
SELECT scores.*, rank() OVER (ORDER BY points DESC)
FROM scores
```

These records will come back sorted by their rank (determined by the `ORDER BY`
in the `OVER` clause. If you wanted to get the top score back from within ActiveRecord
, you could use the following query to get the top score with it's rank:

```ruby
Score.select(:score, 'rank() OVER (ORDER BY points DESC)').first
```

The problem with this query is the fact that since there is no explicit
order called on it via `order()`, when `find_first` gets called, the
sorting by primary key will alter the order of the results, returning
the incorrect "first" result.