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 |
This is neat, clever and simple! Love it!
@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. :)
@jeffkreeftmeijer well, thats a nicer example, which I didn't think about, so I give it a thumbs up.
I don't really see the advantage of this over find(1)