首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用ActionController::Metal处理ActiveRecord::RecordNotFound

用ActionController::Metal处理ActiveRecord::RecordNotFound
EN

Stack Overflow用户
提问于 2013-04-12 16:11:43
回答 1查看 1.4K关注 0票数 3

我正处于开发(JSON) API阶段,并决定从ActionController::Metal继承我的ActionController::Metal,以利用速度等优势。

因此,我已经包括了一系列的模块,以使其工作。

最近,我决定在未找到记录时使用空结果进行响应。Rails已经将ActiveRecord::RecordNotFoundModel#find方法中抛出,我一直试图使用rescue_from来捕获它并编写如下所示的内容:

代码语言:javascript
复制
module Api::V1
  class ApiController < ActionController::Metal
    # bunch of included modules 

    include ActiveSupport::Rescuable

    respond_to :json

    rescue_from ActiveRecord::RecordNotFound do
      binding.pry
      respond_to do |format|
        format.any { head :not_found }
      end
    end
  end
end  

打电话给我简单的动作

代码语言:javascript
复制
def show
  @post = Post.find(params[:id])
end

执行永远不会到达rescue_from。它是扔的:

代码语言:javascript
复制
ActiveRecord::RecordNotFound (Couldn't find Post with id=1

进入我的日志文件。

我试过了,在生产模式下。服务器使用404进行响应,但是响应体是标准的HTML错误页面,用于JSON请求。

当我将继承从ActionController::Metal更改为ActionController::Base时,效果很好。

您可能会注意到缺少respond_with调用。这是因为我使用拉布尔作为我的模板系统。

因此,问题是:是否有机会让rescue_fromMetal一起工作,或摆脱Metal的响应?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-01 19:16:18

以下几点对我有用:

代码语言:javascript
复制
class ApiController < ActionController::Metal
  include ActionController::Rendering
  include ActionController::MimeResponds
  include ActionController::Rescue

  append_view_path Rails.root.join('app', 'views').to_s
  rescue_from ActiveRecord::RecordNotFound, with: :four_oh_four

  def four_oh_four
    render file: Rails.root.join("public", "404.html"), status: 404
  end
end
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15976146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档