Ordering by ID is not guaranteed by default. It’s up to the database how a non-ordered query gets ordered (typically it’s unspecified). If you want your results to be ordered, you need to specify an explicit order with order
, as you’ve done:
Model.order(id: :asc)
Note also that ordering by id
should only be done if you want a deterministic order. If you want to order by time, use created_at
or updated_at
(nothing guarantees that id
s are chronologically ordered). If you want all queries to always be ordered, you could use default_scope
, but generally its use should be avoided.