加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 通过ArraySerializer新语法传入选项哈希

发布时间:2020-12-17 02:06:59 所属栏目:百科 来源:网络整理
导读:是否可以像这样调用ArraySerializer构造函数: mi_tmp[:notes]=ActiveModel::ArraySerializer.new(mi.notes,each_serializer: NotesSerializer,show_extra:false) 然后在序列化器中: ..... if @options[show_extra] attributes :user_id end 我收到错误: E
是否可以像这样调用ArraySerializer构造函数:

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

然后在序列化器中:

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

我收到错误:

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

但是找不到使用这种语法的例子.谢谢

编辑1

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

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

解决方法

这可能对您有所帮助,对我来说也很好

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读