在 activemodel 序列化程序中使用带有条件的属性

Use attribute with condition in activemodel serializer

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title
end

我在某些条件下使用 activemodel 序列化程序 return title 属性。通常我可以覆盖 title 方法,但我想要的是确定 title 属性是否 returned 或不带条件。

我不确定你的具体用例是什么,但也许你可以使用非常神奇的 include_ 方法!他们是最酷的!

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title

  def include_title?
    object.title.present?
  end
end

如果 object.title.present?true,则序列化程序将返回 title 属性。如果是 falsetitle 属性将被完全删除。请记住,include_ 方法带有它自己的特定功能并自动执行操作。它不能在序列化程序的其他地方调用。

如果您需要能够调用该方法,您可以创建自己的 "local" 方法,您可以在序列化程序中使用该方法。

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title

  def title?
    object.title.present?
  end
end

同样,不确定您正在寻找什么功能,但希望这能让您朝着正确的方向前进。