Conditional attributes in Active Model Serializers

前端 未结 5 1226
盖世英雄少女心
盖世英雄少女心 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:52

    you can override the attributes method, here is a simple example:

    class Foo < ActiveModel::Serializer
    
      attributes :id
    
      def attributes(*args)
        hash = super
        hash[:last_name] = 'Bob' unless object.persisted?
        hash
      end
    
    end
    

提交回复
热议问题