Simple respond_with in rails that avoids 204 from PUT

前端 未结 6 502
有刺的猬
有刺的猬 2020-12-23 17:46

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

class SomeController < ApplicationController
  respond_         


        
6条回答
  •  长情又很酷
    2020-12-23 18:11

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

    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
    

    You should now get JSON encoded resources back on PUT.

提交回复
热议问题