gpt4 book ai didi

json - 使用 ActionController::Metal 处理 ActiveRecord::RecordNotFound

转载 作者:行者123 更新时间:2023-12-04 22:07:33 24 4
gpt4 key购买 nike

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

所以我包含了一堆模块来让它工作。

最近我决定在找不到记录时以空结果响应。 Rails 已经从 Model#find 方法中抛出 ActiveRecord::RecordNotFound 并且我一直在尝试使用 rescue_from 来捕获它并编写类似这样的东西:

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

调用我的简单 Action 后

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

并且执行永远不会到达 rescue_from。它的抛出:

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

进入我的日志文件。

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

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

您可能会注意到缺少 respond_with 调用。那是因为我正在使用 RABL作为我的模板系统。

所以问题是:是否有机会使 rescue_fromMetal 一起工作或从响应中删除 HTML?

最佳答案

以下对我有用:

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

关于json - 使用 ActionController::Metal 处理 ActiveRecord::RecordNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15976146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com