I have an attribute (which is a function) and use a specific serializer using Active Model Serializers

StackOverflow https://stackoverflow.com/questions/22822561

سؤال

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?

هل كانت مفيدة؟

المحلول 2

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

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top