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
We are converting our Rails API JSON keys from snake_case to camelCase. We have to do the conversion incrementally, i.e. some APIs work with snake_case while the others change to using camelCase.
Our solution is that we
ActionController::Parameters#deep_snakeize
ApplicationController#snakeize_params
before_action :snakeize_params
only for the controller actions that handle incoming request with camelCase keysYou can try vochicong/rails-json-api for a fully working Rails app example.
# File: config/initializers/params_snakeizer.rb
# Transform JSON request param keys from JSON-conventional camelCase to
# Rails-conventional snake_case
module ActionController
# Modified from action_controller/metal/strong_parameters.rb
class Parameters
def deep_snakeize!
@parameters.deep_transform_keys!(&:underscore)
self
end
end
end
# File: app/controllers/application_controller.rb
class ApplicationController < ActionController::API
protected
# Snakeize JSON API request params
def snakeize_params
params.deep_snakeize!
end
end
class UsersController < ApplicationController
before_action :snakeize_params, only: [:create]
# POST /users
def create
@user = User.new(user_params)
if @user.save
render :show, status: :created, location: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
end