2011-10-12 81 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