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

后端 未结 14 892
灰色年华
灰色年华 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:33

    Solution for Rails 5

    before_action :underscore_params!
    
    def underscore_params!
      underscore_hash = -> (hash) do
        hash.transform_keys!(&:underscore)
        hash.each do |key, value|
          if value.is_a?(ActionController::Parameters)
            underscore_hash.call(value)
          elsif value.is_a?(Array)
            value.each do |item|
              next unless item.is_a?(ActionController::Parameters)
              underscore_hash.call(item)
            end
          end
        end
      end
      underscore_hash.call(params)
    end
    

提交回复
热议问题