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

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

    Example with camelCase to snake_case in rails console

    2.3.1 :001 > params = ActionController::Parameters.new({"firstName"=>"john", "lastName"=>"doe", "email"=>"john@doe.com"})
    => "john", "lastName"=>"doe", "email"=>"john@doe.com"} permitted: false>
    
    2.3.1 :002 > params.transform_keys(&:underscore)
    => "john", "last_name"=>"doe", "email"=>"john@doe.com"} permitted: false>
    

    source:

    http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-transform_keys http://apidock.com/rails/String/underscore

    UPDATE:

    If you have nested attributes and Rails 6 you can do:

    ActionController::Parameters convert to hash and then do deep transform:

    params.permit!.to_h.deep_transform_keys { |key| key.to_s.underscore } params.permit!.to_h.deep_transform_values { |value| value.to_s.underscore }

    Please see:

    http://apidock.com/rails/v6.0.0/Hash/deep_transform_values http://apidock.com/rails/v6.0.0/Hash/deep_transform_keys

提交回复
热议问题