Ruby on rails 通过ArraySerializer新语法传入选项哈希
可以这样调用ArraySerializer构造函数吗:Ruby on rails 通过ArraySerializer新语法传入选项哈希,ruby-on-rails,ruby-on-rails-3.2,active-model-serializers,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_extr
mi_tmp[:notes]=ActiveModel::ArraySerializer.new(mi.notes, each_serializer: NotesSerializer, show_extra:false)
然后在序列化程序中:
.....
if @options[show_extra]
attributes :user_id
end
我得到一个错误:
错误:未定义的局部变量或方法“show_extra”
注释序列化程序:类
但是找不到使用这种语法的示例
编辑1
第一件事我尝试了,但没有运气:
mi_tmp[:notes]=ActiveModel::ArraySerializer.new(mi.notes, each_serializer: NotesSerializer, @options{ show_extra: false } )
如果您想动态地序列化属性,您需要使用magic include\u xxx?方法:
class NotesSerializer < ActiveModel::Serializer
attributes :user_id
def include_user_id?
@options[:show_extra]
end
end
class NotesSerializer
这可能对您有帮助,对我来说工作也很好
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
类BookSerializer@options[:show_extra]
呢?(使用一个符号作为散列的键,而不是变量show_extra
)thx-I使用我首先尝试的语法进行了更新,但没有成功