I've got a strange issue on a Heroku deployment that I can't seem to duplicate locally. Basically when I find all on a specific model instead of sorting by ID it seems to return them in no order at all.
Typically the records come out like so:
>> Model.all
=> [<model id: 2>,<model id: 1>,<model id: 3>,<model id: 4>,<model id: 5>]
... and so on.
If I explicitly call Model.order("id ASC")
it returns the models as expected.
What gives? Why would find all not return the objects in descending ID order?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With