简体   繁体   中英

Active Model Serializer with different serializer for each model

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM