-
Notifications
You must be signed in to change notification settings - Fork 21.9k
Description
Imported from Lighthouse. Original ticket at: http://rails.lighthouseapp.com/projects/8994/tickets/3565
Created by Stephen Celis - 2011-02-22 08:32:35 UTC
The convenience methods @.first@ and @.last@ on @ActiveRecord::Base@ have had me itching to pass in an integer limit as you can with @array#first@ and @#last@. E.g.,
array = [1, 2, "buckle", :my, Shoe]
array.first # => 1
array.first(2) # => [1, 2]
array.first(1) # => [1]
array.last(2) # => [:my, Shoe]
Attached is a patch that adds this functionality.
Person.first # => #<Person id: 1>
Person.first(2) # => [#<Person id: 1>, #<Person id: 2>]
Person.first(1) # => [#<Person id: 1>]
Person.last(2) # => [#<Person id: 49>, #<Person id: 50>]
Considerations:
ActiveRecord::Base subclasses are not kinds of Array, but named scopes and association proxies come closer. Consider the following:
>> Person.scoped({}).first # SELECT * FROM `people` LIMIT 1
=> #<Person>
>> Person.scoped({}).first(2) # SELECT * FROM `people`
=> [#<Person>, #<Person>]
The first gets special treatment. The second does not. In order to make the second consistent, it only makes sense to add the behavior to @ActiveRecord::Base@ as well. (Named scope functionality requires additions to this patch, but I'd prefer a consensus before making any more changes.)
Additionally, it made the most sense to add logic through to @ActiveRecord.find_initial@, rather than merely to the convenience, surface methods, but this obviously could cause problems for those who have been blindly passing options hashes to @find(:first)@ and @:last@ that include a @:limit@. I'm open to the idea of a less-invasive approach that merely adds the functionality to the convenience methods, but this seemed less desirable and messier.
If this is of interest to others, it could also be added to @ActiveResource::Base@.