【问题标题】:Use attribute with condition in activemodel serializer在 activemodel 序列化程序中使用带条件的属性
【发布时间】:2015-07-23 17:39:33
【问题描述】:
class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title
end

我使用 activemodel 序列化程序在某些条件下返回标题属性。通常我可以覆盖 title 方法,但我想要的是确定是否返回 title 属性。

【问题讨论】:

    标签: ruby-on-rails ruby active-model-serializers


    【解决方案1】:

    我不确定您的用例到底是什么,但也许您可以使用神奇的include_ 方法!他们是最酷的!

    class ProjectSerializer < ActiveModel::Serializer
      attributes :id, :title
    
      def include_title?
        object.title.present?
      end
    end
    

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

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

    class ProjectSerializer < ActiveModel::Serializer
      attributes :id, :title
    
      def title?
        object.title.present?
      end
    end
    

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

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多