Reputation: 1310
My project is hosted on Heroku.
I was surprised when Room.all
method returned objects with first object with ID 2
and only then a second object with ID 1
. I thought that there were some sort of guarantee that objects are returned already ordered by ID. Should I always call Room.all.order(:id)
instead of regular all
method?
irb(main):002:0> Room.all
=> #<ActiveRecord::Relation [
#<Room id: 2, color: "rgb(83, 180, 83)", status: "Status #2", created_at: "2014-10-11 14:14:02", updated_at: "2014-10-11 14:18:19">,
#<Room id: 1, color: "rgb(0, 96, 255)", status: "Status #3", created_at: "2014-10-11 14:14:02", updated_at: "2014-10-11 14:18:30">
]>
Upvotes: 1
Views: 260
Reputation: 3963
Nope. Room.all
just ends up with the SQL SELECT * FROM rooms;
- no order is there. In this event, the order of the records is determined by the database (for instance, in PostgreSQL, I notice it returns me the most recently updated records last).
If you want to ensure there's an order when you call .all
, add a default scope which adds it:
default_scope order('rooms.id ASC')
Upvotes: 3