CheeseFry CheeseFry - 1 year ago 79
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.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download