Search code examples
ruby-on-railsruby-on-rails-4active-model-serializers

Rails ActiveModelSerialzer include with transform_key


I have ZoneSerializer

class Api::V1::ZoneSerializer < ActiveModel::Serializer
  attributes :id, :name, :address, :description, :groupname, :key, :speed_limit

  has_many :radius_user_groups
end

And I set transform_key

ActiveModel::Serializer.config.key_transform = :camel_lower

When I get response from server I get radiusUserGroups which is ok. But frontend sends also radiusUserGroups for includes, but there seems to be no autotransform feature for backend. Should I do this manually?


Solution

  • Add in your Application controller This method convert all params to snake_case :

    before_action :deep_snake_case_params!
    
      def deep_snake_case_params!(val = params)
        case val
        when Array
          val.map {|v| deep_snake_case_params! v }
        when Hash
          val.keys.each do |k, v = val[k]|
            val.delete k
            val[k.underscore] = deep_snake_case_params!(v)
          end
          val
        else
          val
        end
      end