如您所知,JSON命名惯例主张使用camelSpace,而Rails主张使用snake_case作参数名称.
在rails控制器中将所有请求的参数转换为snake_case的最佳方式是什么?
由此:
{ ... "firstName": "John","lastName": "Smith","moreInfo": { "mealType": 2,"mealSize": 4,... } }
到这个:
{ ... "first_name": "John","last_name": "Smith","more_info": { "meal_type": 2,"meal_size": 4,... } }
谢谢
解决方法
完成以下步骤后,通过JSON请求提交的camelCase参数名称将更改为snake_case.
例如,一个名为passwordConfirmation的JSON请求参数将在控制器中作为params [:password_confirmation]
在config / initializers / json_param_key_transform.rb创建一个初始化器.此文件将仅更改JSON请求的参数解析行为(JSON请求必须具有请求标头Content-Type:application / json).
找到您的Rails版本并选择下面相应的部分(在Gemfile.lock中找到您的Rails版本):
仅适用于Rails 5
对于Rails 5,将骆驼案例的param键转换为snake-case,将其放在初始化器中:
# 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] = -> (raw_post) { # Modified from action_dispatch/http/parameters.rb data = ActiveSupport::JSON.decode(raw_post) data = {:_json => data} unless data.is_a?(Hash) # Transform camelCase param keys to snake_case: data.deep_transform_keys!(&:underscore) }
对于Rails 4.2(也许更早版本)
对于Rails 4.2(也许更早的版本),要将camel-case参数键转换为snake-case,请将其放在初始化程序中:
# 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 } )
所有Rails版本的最后一步
重新启动rails服务器.