2011-10-12 84 views
1

我是Rails的新手,我写了几个模型。由模型生成的XML之一看起来像这样:在Rails中自定义XML生成

<book> 
    <read type="boolean">true</read> 
    <title>Julius Caesar</title> 
    <id type="integer">1</id> 
</book> 

序列化的XML是好的,但我想有更多的控制权。我想以不同的格式生成相同的文件。像:

<book read="true" id="1"> 
    <title>Julius Caesar</title> 
</book> 

我该如何实现这一目标?我做了一些研究,发现应覆盖to_xml方法。但我不知道该怎么做。

回答

1

对此,您可以使用自定义::Builder::XmlMarkup。但是,the documentation about Active Record Serialization(请参阅最后一个代码示例)是错误的。你可以这样做:

class Book < ActiveRecord::Base 
    def to_xml(options = {}) 
    # Load builder of not loaded yet 
    require 'builder' unless defined? ::Builder 

    # Set indent to two spaces 
    options[:indent] ||= 2 

    # Initialize Builder 
    xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent]) 

    # This is were the real action starts 
    xml.book :read => read, :id => id do 
     xml.title self.title 
    end 
    end 
end 
+0

我还提交了一个pull请求来修复文档:https://github.com/rails/rails/pull/4926 – iblue