0

invoice_serializer.rb

class InvoiceSerializer < ActiveModel::Serializer

  attributes :id, :document_no, :customer_id, :currency_id, :date,
    :due_date, :notes, :invoice_status_id, :total, :tax_total, :grand_total

  # This is not working, associated objects are still rendered
  unless @object.respond_to? :count
    has_many :invoice_lines 
  end

  has_many :invoice_payments

  has_one :customer
  has_one :invoice_status

end

This is my serializer class. I have two 'has_many' associations and I don't want them in a collection. I only want them in singular form. Just to be more clear, I don't want has_many association in invoices#index, it affects performance in a bad way but I want them in invoices#show, invoices#edit actions.

How do I achieve that? How can I associate models conditionally?

turhanco
  • 941
  • 10
  • 19

1 Answers1

0

My gut reaction would be to create another serializer and extend this one, adding has_many :invoice_payments to it.

Then simply use the extended controller when you want the associations, and the original one when you don't.

def InvoiceIndexSerializer < InvoiceSerializer has_many :invoice_payments end

(NB: untested)

This way your serializer stays ignorant of an outside state like which action you're using.

gdpelican
  • 568
  • 4
  • 12