to_xml使用额外的方法返回Rails / ActiveRecord中的哈希

时间:2011-04-08 19:45:26

标签: ruby-on-rails activerecord xml-serialization

我的课程类似:

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>

1 个答案:

答案 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