Reputation: 19873
When calling User.last
it looks like Active Record sorts by id
.
User Load (1.4ms) SELECT * FROM
usersORDER BY users.id DESC LIMIT 1
But when calling User.first
it doesn't use an order clause.
User Load (1.9ms) SELECT * FROM
usersLIMIT 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 * FROM
usersLIMIT 1
guaranteed to return the user with the lowest id?
Upvotes: 0
Views: 205
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
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