Deterministic ordering of records by created_at timestamp

Posted Over 9 years ago. Visible to the public. Repeats.

Creating records in specs can be so fast that two records created instantly after one another might have the same created_at timestamp (especially since those timestamps don't have an indefinitely high resolution). When ordering lists by timestamps, you should therefore always include a final order condition using the primary key of the table.

class Photo < ActiveRecord::Base
  scope :by_date, -> { order('created_at DESC, id DESC') }
end

Photo.by_date

Remember to include the id field in the database index.

Thomas Klemm
Last edit
Over 1 year ago
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Klemm to makandra dev (2014-10-24 12:08)