如何覆盖ActiveRecord :: RecordNotFound的to_json?

时间:2013-12-13 10:01:15

标签: ruby-on-rails

lib / error.rb模块有以下代码:

  class ActiveRecord::RecordNotFound 
    def to_json
      { result_code: 5 }
    end
  end

以下代码捕获异常:

rescue ActiveRecord::RecordNotFound => e
  render json: e
end

但结果是我有一个空哈希。我该如何解决?

1 个答案:

答案 0 :(得分:0)

用这种方法想要实现的目标还不是很清楚。为什么不尝试捕获基本api控制器中的错误(如果有的话)

 class BaseApiController < ActionController::Base

      rescue_from ActiveRecord::RecordNotFound  do |e|
          render :json => {"ErrorType" => "Record Not Found", "message" => e.message},
       :code => :bad_request
      end

 end