Posted over 5 years ago. Visible to the public. Repeats.

Deterministic ordering of records by created_at timestamp

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.

Copy
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.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Thomas Klemm
Last edit:
22 days ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Thomas Klemm to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more