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

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

    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.

    0 讨论(0)
  • 2020-12-23 00:36

    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

    • create method ActionController::Parameters#deep_snakeize
    • create method ApplicationController#snakeize_params
    • set before_action :snakeize_params only for the controller actions that handle incoming request with camelCase keys

    You 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
    
    0 讨论(0)
提交回复
热议问题