序列化自定义属性
Serializing a custom attribute
我正在为我的应用程序使用 Active Model Serializer
gem。现在我遇到这种情况,用户可以拥有一个头像,它只是媒体的 ID。
我把头像信息保存到Redis中了。所以目前我在序列化 JSON 中完全显示头像是这样的:
class UserSerializer < ActiveModel::Serializer
包括头像
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
结束
我查询 Redis 以了解在数据库中寻找什么介质,然后在 :avatar
键中使用结果。
代码下方还有一行注释掉了,这是我在 https://github.com/rails-api/active_model_serializers/ 页面上找到的关于在序列化程序内部使用自定义序列化程序的唯一方法。
所以要解决我的问题。现在 :avatar
就像它在数据库中一样出现,但我希望在将其作为 JSON 提供之前对其进行序列化。
在这种情况下我该怎么做?
您需要序列化头像Class:
class Avatar
def active_model_serializer
AvatarSerializer
end
end
那你就这样用:
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
根据文档,如果您想要自定义序列化程序,您只需添加:
render json: avatar, serializer: AvatarSerializer
或者无论你的序列化程序名称是什么,这里是文档:
https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md#scope
我正在为我的应用程序使用 Active Model Serializer
gem。现在我遇到这种情况,用户可以拥有一个头像,它只是媒体的 ID。
我把头像信息保存到Redis中了。所以目前我在序列化 JSON 中完全显示头像是这样的:
class UserSerializer < ActiveModel::Serializer 包括头像
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
结束
我查询 Redis 以了解在数据库中寻找什么介质,然后在 :avatar
键中使用结果。
代码下方还有一行注释掉了,这是我在 https://github.com/rails-api/active_model_serializers/ 页面上找到的关于在序列化程序内部使用自定义序列化程序的唯一方法。
所以要解决我的问题。现在 :avatar
就像它在数据库中一样出现,但我希望在将其作为 JSON 提供之前对其进行序列化。
在这种情况下我该怎么做?
您需要序列化头像Class:
class Avatar
def active_model_serializer
AvatarSerializer
end
end
那你就这样用:
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
根据文档,如果您想要自定义序列化程序,您只需添加:
render json: avatar, serializer: AvatarSerializer
或者无论你的序列化程序名称是什么,这里是文档:
https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md#scope