0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
timpone
  • 19,235
  • 36
  • 121
  • 211

2 Answers2

3

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
apneadiving
  • 114,565
  • 26
  • 219
  • 213
1
class MenuNotesSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :notes, serializer: NoteSerializer
end
Logan Serman
  • 29,447
  • 27
  • 102
  • 141
  • thx, I guess has_many in Serializers are somewhat disconnected from has_many's in the model? have to wait a few – timpone Apr 02 '14 at 20:46