活动模型序列化程序中的条件属性 [英] Conditional attributes in Active Model Serializers

查看:38
本文介绍了活动模型序列化程序中的条件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在某些条件为真时呈现属性?

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.

推荐答案

你也可以这样做:

class EntitySerializer < ActiveModel::Serializer
  attributes :id, :created_at, :updated_at
  attribute :conditional_attr, if: :condition?

  def condition?
    #condition code goes here
  end
end

例如:

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

编辑(由 Joe Essey 建议) :

此方法不适用于最新版本 (0.10)

使用 0.8 版本,它甚至更简单.您不必使用 if: :condition?.相反,您可以使用以下约定来实现相同的结果.

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

有关详细信息,请参阅 0.8 文档.

See 0.8 documentation for more details.

这篇关于活动模型序列化程序中的条件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆