Brian Armstrong
Brian Armstrong

Reputation: 19873

Does Active Record's first method sort by id?

When calling User.last it looks like Active Record sorts by id.

User Load (1.4ms) SELECT * FROMusersORDER BY users.id DESC LIMIT 1

But when calling User.first it doesn't use an order clause.

User Load (1.9ms) SELECT * FROMusersLIMIT 1

So is this guaranteed to return the User with the lowest id? It seems to in practice but I'm not sure if MySQL guarantees this.

Or do you have to do this: User.first(:order => 'id') which forces the order clause.

Edit: I guess this is really a MySQL question. Is SELECT * FROMusersLIMIT 1 guaranteed to return the user with the lowest id?

Upvotes: 0

Views: 205

Answers (2)

Tadas T
Tadas T

Reputation: 2637

It will return the same result as

select * from users limit 1

so its up to your database how to order data. i.e. you have to add any of above mentioned order methods.

Upvotes: 0

Thilo
Thilo

Reputation: 17735

Not sure what ActiveRecord does by default, but you can force a default order in your model using ActiveRecord's default_scope method:

default_scope :order => "id ASC"

or in Rails 3

default_scope order("id ASC")

Upvotes: 1

Related Questions