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

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?


Solution

  • 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