Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Find All not sorting by ID?

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?

like image 613
Andrew Avatar asked Feb 13 '11 19:02

Andrew


1 Answers

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 ids are chronologically ordered). If you want all queries to always be ordered, you could use default_scope, but generally its use should be avoided.

like image 191
Andrew Marshall Avatar answered Oct 05 '22 01:10

Andrew Marshall