Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Rails 3 dynamic finder to throw RecordNotFound exception?

Is is possible to force a Rails dynamic finder to throw an ActiveRecord::RecordNotFound exception rather than return nil when it cannot find a result?

For example, where a beverage of the name 'Nuka–Cola' does not exist:

@not_found = Beverage.find_by_name('Nuka–Cola')

Rather than having

@not_found == nil

Could the

.find_by_name('Nuka–Cola')

method call throw an ActiveRecord::RecordNotFound exception?

Or am I going to have to check for nil and throw the exception manually?

like image 580
stephenallred Avatar asked Feb 22 '11 21:02

stephenallred


1 Answers

Use the bang version.

@not_found = Beverage.find_by_name!('Nuka–Cola')
like image 140
Simone Carletti Avatar answered Oct 24 '22 07:10

Simone Carletti