Force Rails 3 dynamic crawler to throw RecordNotFound exception?

Is it possible to make a dynamic Rails crawler throw an ActiveRecord::RecordNotFound exception rather than return nil when it cannot find the result?

For example, where a drink named "Nuka-Cola" does not exist:

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

Instead

 @not_found == nil 

Can

 .find_by_name('Nuka–Cola') 

throw throw method call ActiveRecord::RecordNotFound ?

Or will I need to check nil and throw an exception manually?

+8
ruby ruby-on-rails activerecord exception
source share
2 answers

Use the bang version.

 @not_found = Beverage.find_by_name!('Nuka–Cola') 
+21
source share

Thank you very much mask

This will be more useful if you are working on some REST API products. instead of showing an html exception page, render meaningful JSON or XML.

 class ApiController < ApplicationController rescue_from ActiveRecord::RecordNotFound, :with => :not_found def not_found(exception = nil) render :json => { :message => exception.message, :request => request.fullpath }, :status => 404 end end 
-2
source share

All Articles