timpone
timpone

Reputation: 19969

Pass in options hash via ArraySerializer new syntax

Is it possible to call the ArraySerializer constructor like this:

  mi_tmp[:notes]=ActiveModel::ArraySerializer.new(mi.notes, each_serializer: NotesSerializer, show_extra:false)

And then in the serializer:

  .....
  if @options[show_extra]
    attributes :user_id
  end

I get the error:

Error: undefined local variable or method `show_extra' for NotesSerializer:Class

but can't find an example using this type of syntax.

Edit 1

First thing I tried but no luck:

  mi_tmp[:notes]=ActiveModel::ArraySerializer.new(mi.notes, each_serializer: NotesSerializer, @options{ show_extra: false } )

Upvotes: 4

Views: 918

Answers (2)

Khalid Alsaadi
Khalid Alsaadi

Reputation: 11

This might be helpfull for you and its work fine for me

1.In books controller

# books contain a collection of books

books = serialize books, BookSerializer, {root: false, user_book_details: user_book_details}

# custom method

def serialize data, serializer, options = {}
    data.map do |d|
      serializer.new(d, options)
    end    
end

2.In book serializer

class BookSerializer < ActiveModel::Serializer

  def initialize object, options = {}
    @user_book_details = options[:user_book_details]
    super object, options
  end

  attributes :id, :title, :short_description, :author_name, :image, :time_ago, :has_audio, :book_state

  # You can access @user_book_details anywhere inside the serializer

end

Upvotes: 1

patrick
patrick

Reputation: 9742

If you want to dynamically have attributes serialized, you need to use the magic include_xxx? methods:

class NotesSerializer < ActiveModel::Serializer
  attributes :user_id

  def include_user_id?
    @options[:show_extra]
  end
end

Upvotes: 0

Related Questions