This project is archived and is in readonly mode.

#3565 open
Stephen Celis

Add limit functionality to find first and last

Reported by Stephen Celis | December 12th, 2009 @ 04:42 PM

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>]


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.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>