Finding with Ruby Rails
by Tyler on Jun.28, 2008, under Programming, Ruby, Ruby on Rails
I’m sure anyone that has spent enough time with Rails has found this little annoyance. The basic find() is pretty simple.
result = Table.find(params[:id])
A select query is performed on Table that seeks the row whose primary key matches the value returned by params[:id] Pretty cool, until it fails
The above code fails and raises an error if no records are found. Handling raised errors is a little bit of pain compared to a couple of if-then-else statements. A better way to find is to use a variation of the following syntax:
result = Table.find(:first,:conditions=> ["id=?",params[:id]])
Instead of throwing a nasty error, result will become nil if no records are found. Then it becomes possible to check if the query was successful by checking if result is not nil instead of catching errors.
