Rails 3: What is the default order of “MyModel.all”?

会有一股神秘感。 提交于 2019-12-23 07:16:16

问题


I know that Job.all returns an array of all jobs.

But, what would be the order ?

Are they ordered by ascending id ?

What Job.first returns ? The documentation says: "Returns the first resource found."

But, what is the looking order ?


回答1:


Pretty sure default order is however the DB decided to return them.

See here for more info.

ActiveRecord Find All not sorting by ID?

If you want them in a specific order, you should do Model.order()




回答2:


There is no order. You should watch your logs while learning about ActiveRecord to see what SQL is being generated. If there's no ORDER BY clause, there's no order. You may find that you get records back in the order in which they were inserted to the database but that's just coincidental and due to implementation within the database server. SQL results are explicitly unordered unless ORDER BY is present.

As for #first, that is also random without an order clause (at least, it is in rails 3).

You can specify the order quite easily:

MyModel.order(:some_attr) # all records sorted by some_attr
MyModel.order(:some_attr).first # First record in sorted order



回答3:


Default order in Rails is not defined. Actually it depends on the databases.




回答4:


It orders the results in the order created (not on created_at in rails).



来源:https://stackoverflow.com/questions/5193076/rails-3-what-is-the-default-order-of-mymodel-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!