CheeseFry CheeseFry - 4 months ago 26
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


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

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

What I've tried

I've tried making
methods linkbut to no avail.

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


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)