Sortable UUIDs and overriding ActiveRecord::Base

First of all, first and last aren't as simple as you seem to think they are: you're completely neglecting the limit argument that both of those methods support.

Secondly, scope is little more than a fancy way of adding class methods that are intended to return queries. Your scopes are abusing scope because they return single model instances rather than queries. You don't want to use scope at all, you're just trying to replace the first and last class methods so why don't you just override them? You'd need to override them properly though and that will require reading and understanding the Rails source so that you properly mimic what find_nth_with_limit does. You'd want to override second, third, ... and the rest of those silly methods while you're at it.

If you don't feel right about replace first and last (a good thing IMO), then you could add a default scope to order things as desired:

default_scope -> { order(:created_at) }

Of course, default scopes come with their own set of problems and sneaking things into the ORDER BY like this will probably force you into calling reorder any time you actually want to specify the ORDER BY; remember that multiple calls to order add new ordering conditions, they don't replace one that's already there.

Alternatively, if you're using Rails6+, you can use Markus's implicit_order_column solution to avoid all the problems that default scopes can cause.


I think you're going about this all wrong. Any time I see M.first I assume that something has been forgotten. Ordering things by id is pretty much useless so you should always manually specify the order you want before using methods like first and last.


Rails 6 (currently in version 6.0.0rc1) comes to rescue with implicit_order_column!

To order by created_at and make .first, .last, .second etc. respect it is as simple as:

class ApplicationRecord < ActiveRecord::Base
  self.implicit_order_column = :created_at
end