ruby on rails - Serializing a custom attribute -
i using active model serializer
gem application. have situation user can have avatar id of medium.
i have avatar info saved redis. show avatar @ in serialized json, 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 know medium in database, , use result in :avatar
key.
down in code there line commented out, way found on https://github.com/rails-api/active_model_serializers/ page using custom serializer inside of serializer.
so problem. right :avatar
comes in database want serialized before serve json. how can in case?
you need serialize avatar class:
class avatar def active_model_serializer avatarserializer end end
then use way:
class userserializer < activemodel::serializer include avatar attributes :id, :name, :email, :role, :avatar def avatar # strange query object avatar = medium.find(object.current_avatar).first avatar.active_model_serializer.new(avatar, {}).to_json end has_many :media, :comments url :user end
Comments
Post a Comment