Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 894
Misha Moroshko Avatar asked Mar 04 '11 11:03

Misha Moroshko


2 Answers

The 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()

like image 64
Doon Avatar answered Oct 05 '22 21:10

Doon


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
like image 39
noodl Avatar answered Oct 05 '22 21:10

noodl