What is the best way to convert all controller params from camelCase to snake_case in Rails?

后端 未结 14 872
灰色年华
灰色年华 2020-12-23 00:02

As you already know, JSON naming convention advocates the use of camelSpace and the Rails advocates the use of snake_case for parameter names.

What is the best way t

14条回答
  •  时光取名叫无心
    2020-12-23 00:32

    you can try this:

    class ApplicationController < ActionController::API
      include ControllerHelper
      before_action :deep_underscore_params!
    
      def deep_underscore_params!(app_params = params)
        app_params.transform_keys!(&:underscore)
        app_params.each do |key, value|
          deep_underscore_params!(value) if value.instance_of?(ActionController::Parameters)
        end
        app_params.reject! { |k, v| v.blank? }
      end
    end
    

提交回复
热议问题