[英]Active Model Serializer with different serializer for each model
我正在使用ActiveModelSerializer 0.10。 我有一个我要序列化的Account
集合。 有没有办法为集合中的每个模型设置特定的序列化器? 我希望我的控制器返回这样的东西:
{"accounts":
[
{"type":"Group","groupname":"A group","internal_info":"Sensitive info"},
{"type":"User","first_name":"Bob","last_name":"Smith","internal_info":"Sensitive info"}
]
}
我的API分为两部分:用户API和管理员API。 用户API使用ActiveModelSerializer自动找到的标准序列化程序。 像这样的东西
render json: @accounts
会返回此(注意不包括敏感信息):
{"accounts":
[
{"type":"Group","groupname":"A group"},
{"type":"User","first_name":"Bob","last_name":"Smith"}
]
}
admin API使用自定义序列化程序(它们包含更多详细信息,例如internal_info
)。 如何在管理API中呈现此类集合? 我知道我可以使用
render json: @accounts, each_serializer: Admin::AccountSerializer
这在大多数情况下都能很好地工作,但在这种特殊情况下,我有两种类型的Account
。 我可以以某种方式对集合中的Group
对象使用Admin::Account::GroupSerializer
,对集合中的User
对象User
Admin::Accounts::UserSerializer
吗?
我最终使用Admin::AccountSerializer
和条件。 欢迎更好的解决方案。
class AccountSerializer < ActiveModel::Serializer
attribute :groupname, if: :a_group?
attribute :first_name, if: :a_user?
attribute :last_name, if: :a_user?
def a_group?
object.class == Group
end
def a_user?
object.class == User
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.