如何避免在 has_one 关联的 Serializer 中嵌套?
How to avoid nesting in Serializer on has_one association?
我有 ProfileSerializer:
class ProfileSerializer < ActiveModel::Serializer
attributes :id, :role, :name
has_one :company
end
然后我得到
{"user": {"id":7,"role":"guest","name":"misa","company":{"id":2,"user_id":7, ...}}
我有机会避免 "company" 嵌套并得到 JSON 这样的:
{"user": {"user_info": {"id":7,"role":"guest","name":"misa"}, "company_info": {"id":2,"user_id":7, ...}}}
你可以试试这个:
class ProfileSerializer < ActiveModel::Serializer
attributes :id, :role, :name, :company_info
def company_info
object.company
end
end
我有 ProfileSerializer:
class ProfileSerializer < ActiveModel::Serializer
attributes :id, :role, :name
has_one :company
end
然后我得到
{"user": {"id":7,"role":"guest","name":"misa","company":{"id":2,"user_id":7, ...}}
我有机会避免 "company" 嵌套并得到 JSON 这样的:
{"user": {"user_info": {"id":7,"role":"guest","name":"misa"}, "company_info": {"id":2,"user_id":7, ...}}}
你可以试试这个:
class ProfileSerializer < ActiveModel::Serializer
attributes :id, :role, :name, :company_info
def company_info
object.company
end
end