views:

58

answers:

2

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.

+1  A: 

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).

cite
A: 

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)
Ben
Can you give a scenario where created_at would be more accurate than id? Is it a faster query? Shouldn't id (which has the primary index) be the easiest thing for the query engine to retrieve first?
camwest
Just ran a test, it looks like SELECT * FROM `packages` ORDER BY created_at LIMIT 1; uses a filesort and a binary search whereas EXPLAIN SELECT * FROM `packages` ORDER BY id LIMIT 1 uses the primary index and no filesort.
camwest
created_at would be more accurate if you weren't using auto-increment integers (like a UUID). Yes, id would certainly be faster, but it feels messier to me. Maybe just my preference.
Ben
Ben, thanks for getting back to me.
camwest