简单的 response_with 在 rails 中避免 PUT 中的 204 [英] Simple respond_with in rails that avoids 204 from PUT

查看:35
本文介绍了简单的 response_with 在 rails 中避免 PUT 中的 204的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想 PUT 到 rails 并避免获得 204.我正在使用这种模式:

I want to PUT to rails and avoid getting a 204. I am using this pattern:

class SomeController < ApplicationController
  respond_to :json

  def update
    # ...
    respond_with(some_object)
  end
end

然而,当我执行 put 更新时,我得到一个 204 返回.我意识到这是完全有效的等,但我明确希望内容回来.我可以像这样在某种程度上覆盖它:

However, when I do a put to update, I get a 204 back. I realize this is completely valid etc, but I explicitly want the content back. I can override it to some extent like this:

def update
  respond_with(some_object) do |format|
    format.json{render json: some_object}
  end
end

但这对于 Rails 来说似乎有点过于动手了.有没有更惯用的方法来避免 204 并请求发回完整内容?这是 Rails 3.2.

but this seems a bit too hands-on for rails. Is there any more idiomatic way of avoiding a 204 and requesting the full content to be sent back? This is Rails 3.2.

总而言之:我想要最大程度地避免 204 的惯用导轨.

In summary: I want maximally idiomatic rails that avoids a 204.

推荐答案

我制作了一个自定义响应器,即使在 PUT/POST 上也始终返回我的 JSON 编码资源.

I made a custom responder which always returns my JSON encoded resource even on PUT/POST.

我将此文件放在 lib/responders/json_responder.rb 中.您的 /lib 目录应该会自动加载.

I put this file in lib/responders/json_responder.rb. Your /lib dir should be autoloaded.

module Responders::JsonResponder
  protected

  # simply render the resource even on POST instead of redirecting for ajax
  def api_behavior(error)
    if post?
      display resource, :status => :created
    # render resource instead of 204 no content
    elsif put?
      display resource, :status => :ok
    else
      super
    end
  end
end

现在,显式修改需要此行为的控制器,或将其放置在应用程序控制器中.

Now, explicitly modify the controller which requires this behavior, or place it in the application controller.

class ApplicationController < ActionController::Base

  protect_from_forgery

  responders :json

end

您现在应该在 PUT 上获取 JSON 编码的资源.

You should now get JSON encoded resources back on PUT.

这篇关于简单的 response_with 在 rails 中避免 PUT 中的 204的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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