如何为 ApplicationController 中 after_action 过滤器中的所有操作渲染 json?

2024-05-17

是否可以在 Rails ApplicationController 中创建一个 after_filter 方法,该方法在每个操作上运行并呈现为 JSON?我正在构建一个 API,并且希望将控制器中的每个操作的输出呈现为 JSON。

客户控制器.rb

def index
  @response = Client.all
end

应用程序控制器.rb

...
after_action :render_json
def render_json
  render json: @response
end

after_action 永远不会执行,代码会中止:

模板丢失。缺少模板客户/索引,...

If the render json: @response移动到控制器操作中,它可以正常工作。

是否有一个过滤器允许我干燥控制器并将渲染调用移至基本控制器?


您无法渲染 after_action/after_filter。 after_action 回调用于执行操作after渲染。所以在 after_action 中渲染已经太晚了。
但你的异常只是因为你错过了 JSON 模板。我建议使用RABL https://github.com/nesquena/rabl(这为您的 JSON 响应提供了很大的灵活性,并且还有一个铁路广播公司 http://railscasts.com/episodes/322-rabl关于它)。那么你的控制器可能看起来像:

class ClientsController < ApplicationController
  def index
    @clients = Client.all
  end
  def show
    @client = Client.find params[:id]
  end
end

并且不要忘记创建您的 Rabl 模板。
例如客户/index.rabl:

collection @clients, :object_root => false

attributes :id
node(:fancy_client_name) { |attribute| attribute.client_method_generating_a_fancy_name }

但如果您仍然想要更具声明性,您可以利用ActionController::MimeResponds.respond_to http://apidock.com/rails/ActionController/MimeResponds/respond_to like:

class ClientsController < ApplicationController
  respond_to :json, :html
  def index
    @clients = Client.all
    respond_with(@clients)
  end
  def show
    @client = Client.find params[:id]
    respond_with(@client)
  end
end

顺便提一句。请注意,如果您将代码放入 after_action 中,这将延迟整个请求。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 ApplicationController 中 after_action 过滤器中的所有操作渲染 json? 的相关文章

随机推荐