Reputation: 509
I'm using ActiveModelSerializer 0.10. I have a collection of Account
s that I want to serialize. Is there some way to set a specific serializer for each model in the collection? I want my controller to return something like this:
{"accounts":
[
{"type":"Group","groupname":"A group","internal_info":"Sensitive info"},
{"type":"User","first_name":"Bob","last_name":"Smith","internal_info":"Sensitive info"}
]
}
My API is divided into two parts: a user API and an admin API. The user API uses the standard serializers which ActiveModelSerializer finds automatically. Something like this
render json: @accounts
would return this (note that sensitive information is not included):
{"accounts":
[
{"type":"Group","groupname":"A group"},
{"type":"User","first_name":"Bob","last_name":"Smith"}
]
}
The admin API uses custom serializers (they includes more details, for instance the internal_info
). How can I render such a collection in my admin API? I know I can use
render json: @accounts, each_serializer: Admin::AccountSerializer
which works perfectly in most cases, but in this particular case I have two types of Account
s. Can I somehow use Admin::Account::GroupSerializer
for Group
objects in the collection and Admin::Accounts::UserSerializer
for User
objects in the collection?
Upvotes: 2
Views: 1028
Reputation: 509
I ended up using Admin::AccountSerializer
and conditions. Better solutions are welcome.
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
Upvotes: 0