Reputation: 312
I am having an issue with ActiveRecord#first seemingly not returning the first record all of the time.
>> Package.first
=> #<Package id: 22, name: "Test Package 4", created_at: "2009-09-11 21:10:54", updated_at: "2009-09-11 21:12:43", image_file_name: "0600-Sponsor.jpg", image_content_type: "image/jpeg", image_file_size: 29433>
What I'd really like to see is:
>> Package.first(:order => :id)
=> #<Package id: 13, name: "Default Package", created_at: "2009-09-03 20:54:08", updated_at: "2009-09-10 20:27:25", image_file_name: "Screen_shot_2009-09-10_at_3.16.59_PM.png", image_content_type: "image/png", image_file_size: 79386>
Does anyone have any idea what the default sort order is? Should I create a default_scope with an :order => :id? I'm not even sure how to reproduce this behaviour on my development machine.
Upvotes: 1
Views: 434
Reputation: 2121
The above answers are not exactly true. According to http://guides.rubyonrails.org/active_record_querying.html 'first' will return the first record, by default sorted by primary key in ascending order.
That being said, I have experienced, this is not always the case in postgresql, when using complex queries. For instance if you sort it before hand or have default scopes.
Cat.order('id desc').first
Then it will not be by ascending order. Also if your model is scoped to another model
Cat.families.first
The can also change the default order.
Upvotes: 1
Reputation: 8348
From the docs:
"You can pass in all the same arguments to this method as you can to find(:first)
"
I would recommend ordering by created_at, though not id, like so:
Package.first(:order => :created_at)
Upvotes: 1
Reputation: 778
SQL doesn't make any guarantees when it comes to the order in which records are retrieved (unless, of course, the ORDER BY
keyword is given).
Upvotes: 1