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

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

    I wanted to use Chris Healds version, but since I am using Rails 4 I have strong_parameters enabled so I had to change it up a bit.

    This is the version that I came up with:

    before_filter :deep_underscore_params!
    
    
    def deep_underscore_params!(val = request.parameters)
      case val
      when Array
        val.map { |v| deep_underscore_params!(v) }
      when Hash
        val.keys.each do |k, v = val[k]|
          val.delete k
          val[k.underscore] = deep_underscore_params!(v)
        end
    
        params = val
      else
        val
      end
    end
    

提交回复
热议问题