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

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

提交回复
热议问题