Marnen Laibow-Koser wrote in post #971320:
...
> You do know that Timesheet.last will return an arbitrary timesheet, and
> that you can't predict which one it returns, right?
That is not entirely true. It is 'Timesheet.first' that would better be
renamed to 'Timesheet.random' ;-) Same goes for Timesheet.find_by_name
(that is really "pick an arbitrary entry with that name").
But 'Timesheet.last' actually has a default ordering on 'id DESC'.
I saw that behavior in Rails 2.3.5 and 3.0.3. Here in 3.0.3:
ruby-1.9.2-p136 :013 > Timesheet.first
=> #<Timesheet id: 1, name: "Jon", date: "2010-12-29", project: "test">
ruby-1.9.2-p136 :014 > Timesheet.last
=> #<Timesheet id: 4, name: "Jon", date: "2010-12-31", project: "test
4">
ruby-1.9.2-p136 :015 > Timesheet.find_by_name('Jon')
=> #<Timesheet id: 1, name: "Jon", date: "2010-12-29", project: "test">
yields:
Timesheet Load (0.2ms) SELECT "timesheets".* FROM "timesheets" LIMIT
1
Timesheet Load (0.2ms) SELECT "timesheets".* FROM "timesheets" ORDER
BY timesheets.id DESC LIMIT 1
Timesheet Load (0.2ms) SELECT "timesheets".* FROM "timesheets" WHERE
("timesheets"."name" = 'Jon') LIMIT 1
This caused us quite some fun at work (e.g. flickering tests at best,
unpredictable results at worst), so I eventually implemented a ".single"
method that barfs loudly if you _expect_ to find only zero or 1 entries
for a certain query or in a certain array and then unexpectly, there are
more entries there ...
For that reason, at work, I advise against the use of:
* .first => replaced by .single
* find_by => replaced by find_all_by().single
HTH,
Peter
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
No comments:
Post a Comment