使用选项配置块进行序列化
我正在使用 serialize_with_options ( http://www.viget.com/extend/ simple-apis-using-serializewithoptions/ )在 Rails 项目中,并按照链接页面上的示例使用命名块进行渲染:
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:无法复制符号”错误。这对我来说很有意义,因为数组尚未配置为使用serialize_with_options。在运行 .to_xml 并渲染所有扬声器 :with_email 时,如何将此标签传递给各个扬声器对象?
I'm using serialize_with_options ( http://www.viget.com/extend/simple-apis-using-serializewithoptions/ ) in a rails project and have been using named blocks for rendering as per the example on the linked page:
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
Then I can call the second block configuration with @speaker.to_xml(:with_email). This works well, however, I'd like to figure out how to call this block when I have an array of objects. For example, the following does not work:
@speakers = Speaker.all
@speakers.to_xml(:with_email)
Which returns a "TypeError: can't dup Symbol" error. This makes sense to me since Array hasn't been configured to use serialize_with_options. How can I get this tag to be passed on to the individual speaker objects when running .to_xml and render all speakers :with_email?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在上面的示例中,@speakers 是一个 Array 对象。您需要在那里实现/覆盖 to_xml 。那我应该工作:
In your above example, @speakers is a Array object. You need to implement / override the to_xml there . Then i should work: