我在rails项目中使用了serialize_with_options(http://www.viget.com/extend/simple-apis-using-serializewithoptions/),并且已根据链接页面上的示例使用命名块进行渲染:
class Speaker < ActiveRecord::Base
# ...
serialize_with_options do
methods :average_rating, :avatar_url
except :email, :claim_code
includes :talks
end
serialize_with_options :with_email do
methods :average_rating, :avatar_url
except :claim_code
includes :talks
end
end
然后我可以使用@ speaker.to_xml(:with_email)调用第二个块配置。这很好用,但是,当我有一个对象数组时,我想弄清楚如何调用这个块。例如,以下内容不起作用:
@speakers = Speaker.all
@speakers.to_xml(:with_email)
返回“TypeError:can not dup Symbol”错误。这对我来说很有意义,因为Array尚未配置为使用serialize_with_options。如何在运行.to_xml并渲染所有发言者时将此标记传递给各个发言人对象:with_email?
答案 0 :(得分:1)
在上面的例子中,@speakers是一个Array对象。你需要在那里实现/覆盖to_xml。那我应该工作:
class Array
def to_xml (with_email)
self.each do |element|
element.to_xml(with_email)
end
end
end