So what did I fix? The problem was in Rails’ default ORM, ActiveRecord. Basically, when we ask for the last row in our table and our table has a default ordering, then ActiveRecord returns the first row instead.
In Rails terms:
Model.first == Model.last #=> evaluates to true
The root of the problem was caused by a side-effect of a previous change. Internally, the method
reverse_order which reverses the order, but due to the new change, the default order is merged back into the SQL generated by Active Record (HT Andrew). So we get:
SELECT "models".* FROM "models" ORDER BY id ASC, id DESC LIMIT 1
Jon suggested the fix: make
reverse_order use the same mechanism that
order uses so that the default ordering isn’t merged twice.
My patch boils down to just that. Mark that the current query is being reverse ordered in
reverse_order, and to the actual reversal of the SQL order clauses when the default scope (default ordering) is merged.
After a couple attempts, I wrote up a decent patch that was committed to the rails code base by Jon.
Off to the issue to fix; and I promise to get it right the first time (at least without failing tests upon submission!). I love being able to give back to open source software!