2
votes

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?

2
Can you explain what you mean by "avatar which is just the if of a medium" please?Max Williams
Must have been a typo, Avatar is just a class I made to get the ID of a medium from Redis. So avatar is just a user chosen medium, which in backend is marked only with medium_id.Kaspar

2 Answers

3
votes

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
0
votes

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