Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...