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

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

    When you've completed the steps below, camelCase param names submitted via JSON requests will be changed to snake_case.

    For example, a JSON request param named passwordConfirmation would be accessed in a controller as params[:password_confirmation]

    Create an initializer at config/initializers/json_param_key_transform.rb. This file is going to change the parameter parsing behaviour for JSON requests only (JSON requests must have the request header Content-Type: application/json).

    Find your Rails version and choose the appropriate section below (find your Rails version in Gemfile.lock):

    For Rails 5 and 6

    For Rails 5 and 6, to convert camel-case param keys to snake-case, put this in the initializer:

    # File: config/initializers/json_param_key_transform.rb
    # Transform JSON request param keys from JSON-conventional camelCase to
    # Rails-conventional snake_case:
    ActionDispatch::Request.parameter_parsers[:json] = lambda { |raw_post|
      # Modified from action_dispatch/http/parameters.rb
      data = ActiveSupport::JSON.decode(raw_post)
    
      # Transform camelCase param keys to snake_case
      if data.is_a?(Array)
        data.map { |item| item.deep_transform_keys!(&:underscore) }
      else
        data.deep_transform_keys!(&:underscore)
      end
    
      # Return data
      data.is_a?(Hash) ? data : { '_json': data }
    }
    

    For Rails 4.2 (and maybe earlier versions)

    For Rails 4.2 (and maybe earlier versions), to convert camel-case param keys to snake-case, put this in the initializer:

    # File: config/initializers/json_param_key_transform.rb
    # Transform JSON request param keys from JSON-conventional camelCase to
    # Rails-conventional snake_case:
    Rails.application.config.middleware.swap(
      ::ActionDispatch::ParamsParser, ::ActionDispatch::ParamsParser,
      ::Mime::JSON => Proc.new { |raw_post|
    
        # Borrowed from action_dispatch/middleware/params_parser.rb except for
        # data.deep_transform_keys!(&:underscore) :
        data = ::ActiveSupport::JSON.decode(raw_post)
        data = {:_json => data} unless data.is_a?(::Hash)
        data = ::ActionDispatch::Request::Utils.deep_munge(data)
    
        # Transform camelCase param keys to snake_case:
        data.deep_transform_keys!(&:underscore)
    
        data.with_indifferent_access
      }
    )
    

    Final step for all Rails versions

    Restart rails server.

提交回复
热议问题