Rails converts empty arrays into nils in params of the request

后端 未结 6 1897
闹比i
闹比i 2021-02-01 12:20

I have a Backbone model in my app which is not a typical flat object, it\'s a large nested object and we store the nested parts in TEXT columns in a MySQL database.

I wa

6条回答
  •  你的背包
    2021-02-01 12:45

    You can re-parse the parameters on your own, like this:

    class ApiController
      before_filter :fix_json_params    # Rails 4 or earlier
      # before_action :fix_json_params  # Rails 5
    
      [...]
    
      protected
    
      def fix_json_params
        if request.content_type == "application/json"
          @reparsed_params = JSON.parse(request.body.string).with_indifferent_access
        end
      end
    
      private
    
      def params
        @reparsed_params || super
      end
    end
    

    This works by looking for requests with a JSON content-type, re-parsing the request body, and then intercepting the params method to return the re-parsed parameters if they exist.

提交回复
热议问题