How to implement multiple different serializers for same model using ActiveModel::Serializers?

前端 未结 4 1680
不知归路
不知归路 2020-12-07 12:00

Let\'s say you\'re implementing a REST API in Rails. When serving a collection, you might want to only include a few attributes:

/people

B

相关标签:
4条回答
  • 2020-12-07 12:08

    You can have multiple serializers for the same model, e.g.

    class SimplePersonSerializer < ActiveModel::Serializer
      attributes :id, :name
    end
    

    and

    class CompletePersonSerializer < ActiveModel::Serializer
      attributes :id, :name, :phone, :email
    end
    

    simple info for people in one controller:

    render json: @people, each_serializer: SimplePersonSerializer
    

    complete info for people in another:

    render json: @people, each_serializer: CompletePersonSerializer
    

    simple info for a single person:

    render json: @person, serializer: SimplePersonSerializer
    

    complete info for a single person:

    render json: @person, serializer: CompletePersonSerializer
    
    0 讨论(0)
  • 2020-12-07 12:08

    Adding to what @phaedryx said, what I do for this is call a method that returns the correct serializer... for your question, I'd use:

    class MyController < ApplicationController
    
      def index
        render json: @people, each_serializer: serializer_method
      end
    
      private
    
      def serializer_method
        defined?(@people) ? PeopleSerializer : PersonSerializer
      end
    
    end
    
    0 讨论(0)
  • 2020-12-07 12:13

    To avoid mixing view concerns into your models (via serialized variations), use the view to render your JSON for each action, much like we do for HTML.

    jbuilder & rabl both fill this data templating need quite nicely.

    Update 2013-12-16: The ActiveModelSerializers library does support defining multiple serializers for one model, as @phaedryx answered later, by using custom serializers.

    0 讨论(0)
  • 2020-12-07 12:19
    class CompletePersonSerializer < ActiveModel::Serializer
      root :person
      attributes :id, :name, :phone, :email
    end
    

    or

    render json: @people, each_serializer: CompletePersonSerializer, root: :person
    
    0 讨论(0)
提交回复
热议问题