inimene
inimene

Reputation: 1650

Serializing a custom attribute

I am using the Active Model Serializer gem for my application. Now I have this situation where a user can have an avatar which is just the ID of a medium.

I have the avatar info saved into Redis. So currently what I do to show the avatar at all in the serialized JSON, is this:

  class UserSerializer < ActiveModel::Serializer
    include Avatar

    attributes :id,
               :name,
               :email,
               :role,
               :avatar

    def avatar
      Medium.find(self.current_avatar)[0]
    end

    #has_one :avatar, serializer: AvatarSerializer

    has_many :media, :comments

    url :user
  end

I query Redis to know what medium to look for in the database, and then use the result in the :avatar key.

Down in the code there is also a line commented out, that was the only way I found on the https://github.com/rails-api/active_model_serializers/ page about using a custom serializer for something inside of serializer.

So to get to my problem. Right now the :avatar comes just like it is in the database but I want it to be serialized before I serve it as JSON. How can I do that in this case?

Upvotes: 2

Views: 3506

Answers (2)

Guilherme Pereira
Guilherme Pereira

Reputation: 366

You need to serialize Avatar Class:

class Avatar
  def active_model_serializer
    AvatarSerializer
  end
end

Then you just use this way:

class UserSerializer < ActiveModel::Serializer
  include Avatar

  attributes :id,
             :name,
             :email,
             :role,
             :avatar

  def avatar
    # Strange you query another object 
    avatar = Medium.find(object.current_avatar).first
    avatar.active_model_serializer.new(avatar, {}).to_json
  end

  has_many :media, :comments

  url :user
end

Upvotes: 3

Daniel Disblu
Daniel Disblu

Reputation: 343

According to the docs if you want a custom serializer you can just add:

render json: avatar, serializer: AvatarSerializer

or whatever your serializer name could be, here are the docs:

https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md#scope

Upvotes: 0

Related Questions