.first and .last on models using uuid

Posted . Visible to the public.

Normally, your rails model is backed by an Integer as ID. So User.first leads to:

SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 1

That does not work with UUIDs (e.g. "028edf8c-c61c-40bc-a11c-27e90a7f373c").

Solution: Define custom methods on the class:

# replacement for .first/.last because we use uuids
def self.first
  order("users.created_at").first
end
  
def self.last
  order("users.created_at DESC").first
end
dirk
Last edit
dirk
Posted by dirk to BitCrowd (2015-10-09 14:11)