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

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

    Another rails 5.1 solution that piggy backs off of the Sebastian Hoitz solution above. To clarify why we need to do this: in R5.1 deep_transform_keys! is no longer a method available to us, since params are no longer inheriting from HashWithIndifferentAccess. And overcomes the issue mentioned by Eliot Sykes where the initializer only works for application/json mime types. It does add overhead to all the requests though. (I'd love to see some initializers for ActionDispatch::Request.parameter_parsers[:multipart_form]) though, since the initializer is a better place to be doing this, IMO.

    before_action :normalize_key!

     def normalize_keys!(val = params)
      if val.class == Array
        val.map { |v| normalize_keys! v }
      else
        if val.respond_to?(:keys)
          val.keys.each do |k|
            current_key_value = val[k]
            val.delete k
            val[k.to_s.underscore] = normalize_keys!(current_key_value)
          end
        end
        val
      end
      val
    end
    

提交回复
热议问题