I am using Active Model Serializers with my Rails 4 API, and I have been trying to figure out how to include the auth_token attribute in my JSON response only when the user logs in at sessions#create. I read the AMS documentation and tried most of the seeming solutions but none worked.
Couple things to point out:
:auth_tokenis not in theUserSerializer's attributes list.- Since the
auth_tokenis controller-specific, I can't do the conditional logic in theUserSerializerunless there is a way to determine what controller was called in the Serializer. So nodef include_auth_token? ... end.
Some of the things I've tried already:
class Api::V1::SessionsController < ApplicationController
if user = User.authenticate(params[:session][:email], params[:session][:password])
if user.active
user.generate_auth_token #=> Custom method
user.save
# Tried using the meta param
render :json => user, :meta => {:auth_token => user.auth_token}
# Tried using the include param both with 'auth_token' and 'user.auth_token'
render :json => user, include: 'user.auth_token'
end
end
end
Ideally, I would like to be able to use something along the lines of render :json => user, :include => :auth_token to additionally include attributes not already defined in the UserSerializer.
What is the proper way to conditionally include attributes from the controller with AMS?