ActiveRecord find_by shortcut

Some of you may have read an article from Jamis Buck a while back entitled ActiveRecord::Base find shortcut.

The tip offered in the article is that with a quick alias_method:

class << ActiveRecord::Base
  alias_method :[], :find

you can save some typing in script/console:

prs = Person[5]
prs = Person[:first]
prs = Person[:all, :conditions => { :name => "Jamis" }]

This is a cool tip but what I find more useful is to define the [] method separately on each ActiveRecord model depending on the most accessed find_by method.

For example I have a site where accounts are identified by unique subdomains. I find myself in the console all the time doing:

>> Account.find_by_subdomain('foobar')

Now with a quick addition to the Account model:

class Account < ActiveRecord::Base
  def self.[](subdomain)
    find_by_subdomain subdomain

we can do:

>> Account['foobar']

Cool stuff. Now we can add the [] method to other models according to their most common lookup attribute.

Another example

class User < ActiveRecord::Base
  def self.[](username)
    find_by_username username

This very simple little tweak has made my script/console life much more bearable.

Comment or question via
FYI: This post was migrated over from another blogging engine. If you encounter any issues please let me know on . Thanks.