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
I couldn't use other suggestions here directly, but it got me on the right track.
With Rails 5.2, using a versioned API and thus unable to change it for the whole application. I created this concern which i then included into the base controller of my new api version module.
module UnderscoreizeParams
extend ActiveSupport::Concern
def process_action(*args)
request.parameters.deep_transform_keys!(&:underscore)
super
end
end
then in my API V3 BaseController
class V3::BaseController
include UnderscoreizeParams
end
enjoy.
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