Posts Tagged ‘find’

ActiveRecord::Base.find(:last) in Rails 2

Thursday, January 17th, 2008

I don’t know about you, but when I see find(:first) I also expect there to be a find(:last). This hack was working in Rails 1.x but broke in Rails 2. So I fixed it. Paste this into environment.rb or wherever:

module ActiveRecord
  class Base
    def self.find_with_last(*args)
      if args.first == :last
        options = args.extract_options!
        find_without_last(:first, options.merge(:order => "#{primary_key} DESC"))
      else
        find_without_last(*args)
      end
    end
 
    class << self # Needed because we are redefining a class method
      alias_method_chain :find, :last
    end    
  end
end

I wouldn’t rely on this in actual production code (for a variety of reasons) but it’s a useful convenience method for script/console, which is where I tended to want this functionality anyway.

>> MyTable.find(:all).length
=> 2076
>> MyTable.find(:first).id
=> 1
>> MyTable.find(:last).id
=> 2076
>> puts "1337"
1337
=> nil