通过ArraySerializer新语法传递选项哈希

时间:2014-08-18 14:15:23

标签: ruby-on-rails ruby-on-rails-3.2 active-model-serializers

是否可以像这样调用ArraySerializer构造函数:

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

然后在序列化器中:

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

我收到错误:

  

错误:未定义的局部变量或方法`show_extra'对于   NotesSerializer:类

但无法找到使用此类语法的示例。 thx

编辑1

我尝试的第一件事但没有骰子:

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

2 个答案:

答案 0 :(得分:1)

这可能对您有所帮助,对我来说工作正常

1.在书籍控制器

# 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.在书籍序列化器中

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

答案 1 :(得分:0)

如果要动态地将属性序列化,则需要使用魔法include_xxx?方法:

class NotesSerializer < ActiveModel::Serializer
  attributes :user_id

  def include_user_id?
    @options[:show_extra]
  end
end