to_xml 带有额外的方法,返回 Rails/ActiveRecord 中的哈希值
我有一个类似这样的类:
class Product < ActiveRecord::Base
# .... some stuff
def prices
# Make hash like { "Regular" => 10, "Discount" => 8 }
end
end
我从数据库中获取它并在其上尝试 to_xml
:
Product.find(id).to_xml(:methods => [:prices])
但是如果价格失败,则哈希
... some XML
<prices>Regular10Discount8</prices>
... some more XML
to_json
按预期工作。
改变格式的最简单方法是什么,最终结果如下:
<prices>
<price name="Regular">10</price>
<price name="Discount">8</price>
</prices>
I have a class something like this:
class Product < ActiveRecord::Base
# .... some stuff
def prices
# Make hash like { "Regular" => 10, "Discount" => 8 }
end
end
I grab this from the database and try to_xml
on it:
Product.find(id).to_xml(:methods => [:prices])
But if fails at the prices hash
... some XML
<prices>Regular10Discount8</prices>
... some more XML
to_json
works as expected.
What's the easiest way to alter the format so it ends up as something like this:
<prices>
<price name="Regular">10</price>
<price name="Discount">8</price>
</prices>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要自己进行
to_xml
格式化:而不仅仅是
Product.find(id).to_xml
I think You're left with doing the
to_xml
formatting Yourself :than just to a
Product.find(id).to_xml