Conditional attributes in Active Model Serializers

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

    Override is a good idea, but if you use the super the attributes will be calculated before you remove what you want. If it does not make difference to you, ok, but when it does, you can use it:

    def attributes(options={})
      attributes =
        if options[:fields]
          self.class._attributes & options[:fields]
        else
          self.class._attributes.dup
        end
    
      attributes.delete_if {|attr| attr == :attribute_name } if condition
    
      attributes.each_with_object({}) do |name, hash|
        unless self.class._fragmented
          hash[name] = send(name)
        else
          hash[name] = self.class._fragmented.public_send(name)
        end
      end
    end
    

    ps: v0.10.0.rc3

提交回复
热议问题