【问题标题】:Conditional serialization based off of value of attribute基于属性值的条件序列化
【发布时间】:2016-06-16 17:32:15
【问题描述】:

我试图限制在序列化程序级别的 json 响应中显示哪些子项。如果一种货币被标记为“活动”,则该货币应包含在商家的有效负载中。如果货币“无效”,则不应包括商家的 GET。

导轨,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 方法link但无济于事。
并创建显示here 的自定义属性。但我仍在努力掌握如何/应该如何做到这一点。

【问题讨论】:

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


    【解决方案1】:

    如果我正确理解了您的问题,您希望 has_many :merchant_currency_maps 仅包含有效的货币地图,对吗?您可以尝试在您的 MerchantSerializer 中覆盖:

    def merchant_currency_maps
      object.merchant_currency_maps.where(active: true)
    end
    

    【讨论】:

    • 这很漂亮。非常感谢。
    【解决方案2】:

    我相信使用它可以让 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 配置为同步它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      相关资源
      最近更新 更多