开发者

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    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜