使用ActionController :: Metal处理ActiveRecord :: RecordNotFound [英] Handling ActiveRecord::RecordNotFound with ActionController::Metal

查看:81
本文介绍了使用ActionController :: Metal处理ActiveRecord :: RecordNotFound的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm on the developing (JSON) API stage and decide to inherit my ApiController from ActionController::Metal to took advantages of speed etc.

因此,我包括了很多模块来使其工作.

So I've included a bunch of modules to make it work.

最近,我决定在找不到记录的情况下以空结果进行响应. Rails已经从Model#find方法中抛出了ActiveRecord::RecordNotFound,我一直在尝试使用rescue_from来捕获它并编写如下内容:

Recently I've decide to respond with empty result when record not found. Rails already throws ActiveRecord::RecordNotFound from Model#find method and I've been trying to use rescue_from to catch it and write something like this:

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  

打电话给我简单的动作

def show
  @post = Post.find(params[:id])
end

执行永远不会达到rescue_from.抛出:

And execution never reach rescue_from. It's throws:

ActiveRecord::RecordNotFound (Couldn't find Post with id=1

进入我的日志文件.

我一直在尝试并在生产模式下使用.服务器以404响应,但是响应正文是 JSON 请求的标准 HTML 错误页面.

I've been trying it and in production mode. Server responds with 404 but response body is standard HTML error page for JSON request.

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

It's works well when I change inheritance from ActionController::Metal to ActionController::Base.

您可能会注意到缺少respond_with呼叫.那是因为我使用 RABL 作为模板系统.

You may notice about lack of respond_with call. That's because I'm using RABL as my template system.

所以问题是:是否有机会使rescue_fromMetal一起使用或摆脱响应中的HTML?

So the question is: Is there any chances to make rescue_from work with Metal or get rid HTML from response?

推荐答案

以下内容对我有用:

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

这篇关于使用ActionController :: Metal处理ActiveRecord :: RecordNotFound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆