CheeseFry CheeseFry - 29 days ago 9
Ruby Question

Conditional serialization based off of value of attribute

I am trying to limit which children get displayed in the json response at the serializer level. If a currency is marked as 'active' the currency should be included in the payload for Merchant. If the currency is 'inactive' the GET on merchant should not be included.

rails, 4.2.5
active_model_serializers, ~>0.10.0.rc3

Serializers

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


What I've tried

I've tried making
include_currency_maps
methods linkbut to no avail.

And creating custom attributes shown here. But I am still struggling to grasp how this can/should be done.

Answer

If I'm understanding your question correctly, you want has_many :merchant_currency_maps to only include currency maps that are active, right? You could try an override in your MerchantSerializer:

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