Active Model Serializers中的条件属性

Dan*_*Dan 40 ruby-on-rails active-model-serializers

如果某些条件为真,我该如何渲染属性?

例如,我想在create action上呈现User的token属性.

Abd*_*ADI 60

你也可以这样做:

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

  def condition?
    #condition code goes here
  end
end
Run Code Online (Sandbox Code Playgroud)

例如:

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
Run Code Online (Sandbox Code Playgroud)

编辑(由Joe Essey推荐):

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

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

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

  def include_conditional_attr?
    #condition code goes here
  end
end
Run Code Online (Sandbox Code Playgroud)

上面的例子看起来像这样.

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
Run Code Online (Sandbox Code Playgroud)

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

  • include_foo?方法从0.10开始不再有效 (4认同)
  • 图书馆已更新。你不再需要`attribute :foo, if: :bar`。只需为您希望有条件地显示的每个属性命名一个函数,例如:`include_foo?` 并在那里进行 bool 检查。它在答案中链接的文档中。 (2认同)
  • 抱歉,需要说明的是,自动 `include_foo?` 方法似乎已被删除——您仍然可以向属性方法添加一个 `if: foo?` 参数。 (2认同)

apn*_*ing 44

你可以覆盖attributes方法,这是一个简单的例子:

class Foo < ActiveModel::Serializer

  attributes :id

  def attributes(*args)
    hash = super
    hash[:last_name] = 'Bob' unless object.persisted?
    hash
  end

end
Run Code Online (Sandbox Code Playgroud)


fro*_*kos 5

您可以首先在序列化器“初始化”方法上设置条件。此条件可以从代码中的其他任何位置传递,包括在“initialize”接受作为第二个参数的选项哈希中:

class SomeCustomSerializer < ActiveModel::Serializer

  attributes :id, :attr1, :conditional_attr2, :conditional_attr2

  def initialize(object, options={})
    @condition = options[:condition].present? && options[:condition]
    super(object, options)
  end

  def attributes(*args)
    return super unless @condition  #get all the attributes
    attributes_to_remove = [:conditional_attr2, :conditional_attr2]
    filtered = super.except(*attributes_to_remove)
    filtered
  end
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,始终会传递 attr1,而如果条件为真,则条件属性将被隐藏。

您将在代码中的任何其他位置获得此自定义序列化的结果,如下所示:

custom_serialized_object = SomeCustomSerializer.new(object_to_serialize, {:condition => true})
Run Code Online (Sandbox Code Playgroud)

我希望这有用!