Search code examples
ruby-on-railsactive-model-serializers

Custom field in ActiveModel Serializer with another serializer


I have User model with has_many :sessions. But for one particular request I want to send only one session based on request device platform (iOS, Android).

The problem is that I have separate UserSerializer and UserSessionSerializer and I want to pass UserSessionSerializer as option in UserSerializer for :session field. Like this:

# UsersController
render json: @user, serializer: UserSerializer, session: @session # @user's session founded by platform

# UserSerializer
attributes :id, :email, :username, :session

def session
  @instance_options[:session], serializer: UserSessionSerializer
end

It is impossible, because I can pass serializer only in has_one and has_many as I understand. But I don't want to render all user sessions in JSON with has_many, only founded one.

Thanks for any help!


Solution

  • Your code is good just use UserSessionSerializer.new instead of serializer: UserSessionSerializer

    render json: { user: UserSerializer.new(@user, session: @session) }
    
    attributes :id, :email, :username, :session
    
    def session
      UserSessionSerializer.new(self.instance_options[:session]) if self.instance_options[:session].present?
    end