基于属性值的条件序列化

Conditional serialization based off of value of attribute

我正在尝试限制在序列化程序级别的 json 响应中显示哪些子项。如果货币标记为 'active',则该货币应包含在商家的有效负载中。如果货币是 'inactive',则不应包括商家的 GET。

rails, 4.2.5 active_model_serializers, ~>0.10.0.rc3

序列化程序

class MerchantSerializer < ActiveModel::Serializer
  attributes :id, :merchant_name, :merchant_type, :currencies
  has_many :merchant_currency_maps
end

class MerchantCurrencyMapSerializer < ActiveModel::Serializer
  attributes :id, :currency, :b4flight_id, :aht_account_id, :created_at, :updated_at, :guess_merchant 
end

我试过的

我试过制作 include_currency_maps 方法 但无济于事。
并创建显示的自定义属性 。但我仍在努力了解如何完成 can/should。

如果我对你的问题的理解正确,你希望 has_many :merchant_currency_maps 只包括活跃的货币地图,对吗?您可以在 MerchantSerializer:

中尝试覆盖
def merchant_currency_maps
  object.merchant_currency_maps.where(active: true)
end

使用它可以让 rails 更好地缓存您的数据我相信:

has_many :merchant_currency_maps, -> { where(active: true) }

或者这样做

has_many :active_merchant_currency_maps,   -> { where(active: true) }
has_many :merchant_currency_maps 
has_many :inactive_merchant_currency_maps, -> { where(active: false) }

每个都将被单独缓存。担心的是 3 个数组中的每一个都有不同的对象,并且可能会变得不同步,除非您将 rails 配置为同步它们。