Question

I have the following Active Model Serializer and would like to use a specific serializer for a method called notes which is returning an array of notes from the instance.

I have tried this and some other variations:

class MenuNotesSerializer < ActiveModel::Serializer
  attributes :id, :name, :notes(NoteSerializer)

and:

class MenuNotesSerializer < ActiveModel::Serializer
  attributes :id, :name, :tns

  def tns
    object.notes  #  works , serializer: NoteSerializer
  end

  def tns
    object.notes, serializer: NoteSerializer #doesn't work
  end

Basically I have a NoteSerializer that I'd like to be used for the array returned by the notes method on menu. How can I achieve this?

Was it helpful?

Solution 2

class MenuNotesSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :notes, serializer: NoteSerializer
end

OTHER TIPS

Here is one other solution for basic arrays (not relations, or when you want a very specific scope):

attributes :tns

def tns
  object.notes.map do|note|
    NoteSerializer.new(note, scope: scope, root: false)
  end
end

Or even:

def tns
  ActiveModel::ArraySerializer.new(object.notes, each_serializer: NoteSerializer)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top