Plugins - Bangin' Finders

StarAdd to favorites

Bangin Finders!

Those who know ActiveRecord are familiar with the dynamic attribute finders. Given a model with attrbutes :foo, :bar and :baz, one gets the following finders, handled via :method_missing:

  * find_by_foo, to search for a single record
  * find_all_by_foo, to search for all records
  * repeat for each attribute...

Those finders act like a search, happily returning nil or an empty Array. Sometimes you may wish to use another attribute than the primary key as the primary identifier in your routes. In that case, you’d have to write your own finder to raise ActiveRecord::RecordNotFound if you want to use the built-in 404-rendering behavior.

Now, you can simply use those familiar dynamic finder names.. with a bang!

  >> Page.find_by_url! 'about'
  => #<Page ...>
  >> Page.find_by_url! 'aboutyourmom'
  ActiveRecord::RecordNotFound: no record(s) found for "find_by_url" with ["aboutyourmom"]

This could be useful for a simple, friendly URL system where, when given a params[:id] of ‘Bort’ and having no users by that name, you’d like to raise as if you were doing a :find on the primary key.

This simple bit of hackery was created by Seth Thomas Rasmussen near the end of January in the year 2008 and released under the WTFPL license. See the LICENSE file and/or http://sam.zoy.org/wtfpl for more information.

Seth Thomas Rasmussen

http://sethrasmussen.com

http://sethrasmussen.com/svn/rails/plugins/bangin_finders

  • Currently 5.0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Model

Tags

Comments

Add a comment

Search Plugins

Query syntax

Plugins by Category

Sponsors

Rails Kits: Get Code. Get Moving.

Have a comment?