【问题标题】:Pass in options hash via ArraySerializer new syntax将选项哈希传递给 Array Serializer 新语法
【发布时间】:2014-08-18 14:15:23
【问题描述】:

是否可以这样调用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:类

但找不到使用这种语法的示例。

编辑 1

我尝试的第一件事但没有运气:

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

【问题讨论】:

  • @options[:show_extra] 怎么样? (使用符号作为哈希的键,而不是变量 show_extra
  • thx - 我用我首先尝试的语法进行了更新,但没有奏效

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


【解决方案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

【讨论】:

    【解决方案2】:

    如果你想动态地序列化属性,你需要使用魔术 include_xxx 吗?方法:

    class NotesSerializer < ActiveModel::Serializer
      attributes :user_id
    
      def include_user_id?
        @options[:show_extra]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 2012-08-25
      • 1970-01-01
      • 2020-06-14
      相关资源
      最近更新 更多