Conditional attributes in Active Model Serializers

前端 未结 5 1166
盖世英雄少女心
盖世英雄少女心 2020-12-08 00:19

How do I render an attribute only if some condition is true?

For example, I want to render User\'s token attribute on create action.

5条回答
  •  攒了一身酷
    2020-12-08 00:59

    You can also do it this way:

    class EntitySerializer < ActiveModel::Serializer
      attributes :id, :created_at, :updated_at
      attribute :conditional_attr, if: :condition?
    
      def condition?
        #condition code goes here
      end
    end
    

    For example:

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :username, :name, :email, :created_at, :updated_at
      attribute :auth_token, if: :auth_token?
    
      def created_at
        object.created_at.to_i
      end
    
      def updated_at
        object.updated_at.to_i
      end
    
      def auth_token?
        true if object.auth_token
      end
    end
    

    EDIT (Suggested by Joe Essey) :

    This method doesn't work with latest version (0.10)

    With the version 0.8 it is even simpler. You don't have to use the if: :condition?. Instead you can use the following convention to achieve the same result.

    class EntitySerializer < ActiveModel::Serializer
      attributes :id, :created_at, :updated_at
      attribute :conditional_attr
    
      def include_conditional_attr?
        #condition code goes here
      end
    end
    

    The example above would look like this.

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :username, :name, :email, :created_at, :updated_at
      attribute :auth_token
    
      def created_at
        object.created_at.to_i
      end
    
      def updated_at
        object.updated_at.to_i
      end
    
      def include_auth_token?
        true if object.auth_token
      end
    end
    

    See 0.8 documentation for more details.

提交回复
热议问题