Rails: Augmenting ActiveRecord::Base#find
Let’s say you want to modify a given ActiveRecord class such that all #find calls will, by default, sort by a given column. I ran into this the other day, and I wasn’t quite sure how to do it. Turns out it’s actually pretty easy (though not 100% trivial for the noob):
class User < ActiveRecord::Base
def self.find(*args)
options = args.extract_options!
options[:order] ||= "last_name ASC, first_name ASC"
super(*args.push(options))
end
end
This snippet will cause User#find calls to by default sort the results first by last_name, then by first_name. If, however, you specify the :order option when calling #find, this method will respect your choice.
Caveat: I’m not sure when Array#extract_options! showed up in Rails’ ActiveSupport library, but it’s at least there as of 2.1.0.
