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

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

    tlewin's answer didn't work for me in Rails 3. it seems the params' = operator renders future operations on it void. very strange. anyways the following works for me, as it only uses the []= and delete operators:

    before_filter :underscore_param_keys
    def underscore_param_keys
      snake_hash = ->(hash) {
        # copying the hash for iteration so we are not altering and iterating over the same object
        hash.to_a.each do |key, value|
          hash.delete key
          hash[key.to_s.underscore] = value
          snake_hash.call(value) if value.is_a? Hash
          value.each { |item| snake_hash.call(item) if item.is_a? Hash } if value.is_a? Array
        end
      }
      snake_hash.call(params)
    end
    

提交回复
热议问题