Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding serializer when using devise_token_auth and active_model_serializer

I am unable to override the Rails serializer when using devise_token_auth and active_model_serializer for Devise sign_up method.

I would like to customize the returned fields from the Devise sign_up controller when querying my API.

The devise_token_auth gem documentation indicates:

To customize json rendering, implement the following protected controller methods

Registration Controller

...

render_create_success

...

Note: Controller overrides must implement the expected actions of the controllers that they replace.

That is all well and good, but how do I do this?

I've tried generating a UserController serializer like the following:

class UsersController < ApplicationController

  def default_serializer_options
    { serializer: UserSerializer }
  end

  # GET /users
  def index
    @users = User.all

    render json: @users
  end

end

but it's only being used for custom methods such as the index method above: it's not being picked up by devise methods like sign_up

I would appreciate a detailed response since I've looked everywhere but I only get a piece of the puzzle at a time.

like image 649
Augusto Samamé Barrientos Avatar asked May 29 '16 22:05

Augusto Samamé Barrientos


1 Answers

For the specific serialiser question, here's how I did it:

overrides/sessions_controller.rb

module Api
  module V1
    module Overrides
      class SessionsController < ::DeviseTokenAuth::SessionsController

        # override this method to customise how the resource is rendered. in this case an ActiveModelSerializers 0.10 serializer.
        def render_create_success
          render json: { data: ActiveModelSerializers::SerializableResource.new(@resource).as_json }
        end
      end
    end
  end
end

config/routes.rb

namespace :api, defaults: {format: 'json'} do
  scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
      mount_devise_token_auth_for 'User', at: 'auth', controllers: {
          sessions: 'api/v1/overrides/sessions'
      }
      # snip the rest
like image 181
a user Avatar answered Sep 30 '22 05:09

a user