我的课程类似:
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>
答案 0 :(得分:2)
我认为你离开了to_xml
格式化你自己:
class Product < ActiveRecord::Base
def prices
...
end
def to_xml(options = {})
super(options) do |xml|
if prices.empty?
xml.tag! 'prices' # empty tag
else
xml.prices do
prices.each do |name, val|
xml.price val, 'name' => name
end
end
end
yield(xml) if block_given?
end
end
end
而不仅仅是Product.find(id).to_xml