Skip to content

Instantly share code, notes, and snippets.

@jamesu
Created July 20, 2011 12:23
Show Gist options
  • Select an option

  • Save jamesu/1094860 to your computer and use it in GitHub Desktop.

Select an option

Save jamesu/1094860 to your computer and use it in GitHub Desktop.
Array operator on ActiveRecord

Array operator on ActiveRecord

This adds a [] operator to ActiveRecord models to quickly find single records, e.g.

User[:id => 1]

Thats it!

# Adds a [] operator to ActiveRecord models
# e.g. User[:id => 1] returns #<User id: 1>
class ActiveRecord::Base
def self.[](val)
self.where(val).first
end
end
@joshk

joshk commented Jul 25, 2011

Copy link
Copy Markdown

I don't really see the advantage of this over find(1)

@inkel

inkel commented Jul 25, 2011

Copy link
Copy Markdown

This is neat, clever and simple! Love it!

@jeffkreeftmeijer

Copy link
Copy Markdown

@joshk maybe not when finding a record by id, it's probably more useful when looking for somebody named "Josh":

User.where(:first_name => 'Josh')
User[:first_name => 'Josh']

It's not much, but it saves you some keystrokes. :)

@joshk

joshk commented Jul 25, 2011

Copy link
Copy Markdown

@jeffkreeftmeijer well, thats a nicer example, which I didn't think about, so I give it a thumbs up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment