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 t开发者_如何学运维he
.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?
Use the bang version.
@not_found = Beverage.find_by_name!('Nuka–Cola')
Thanks a lot, guise
It will be more useful if you are working on some REST API stuffs. instead of showing the 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
精彩评论