2010-02-05 119 views
2

我的用戶模型中有一個序列化的字段叫做options(類型爲Hash)。選項字段在大多數情況下表現得像哈希。當我將用戶對象轉換爲XML時,'選項'字段被序列化爲YAML類型而不是哈希。ActiveRecord序列化屬性中的XML序列化問題

我正在通過REST將結果發送給Flash客戶端。這種行爲在客戶端造成問題。有沒有辦法解決這個問題?

class User < ActiveRecord::Base 
    serialize :options, Hash 
end 

u = User.first 
u.options[:theme] = "Foo" 
u.save 

p u.options # prints the Hash 

u.to_xml # options is serialized as a yaml type: 
      # <options type=\"yaml\">--- \n:theme: Foo\n</options> 

編輯:

我正在解決這個問題,通過傳遞塊to_xml(類似於MOLF建議的解決方案)

u.to_xml(:except => [:options]) do |xml| 
    u.options.to_xml(:builder => xml, :skip_instruct => true, :root => 'options') 
end 

我不知道是否有更好的方法。 。

回答

2

序列化在數據庫中用YAML完成。他們沒有告訴你的是,它也被作爲YAML傳遞給XML序列化器。 serialize的最後一個參數表示您分配options的對象應該是Hash類型。

您的問題的一個解決方案是用您自己的實現覆蓋to_xml。借用原始的xml構建器對象並將其傳遞給options散列的to_xml相對容易。像這樣的東西應該工作:

class User < ActiveRecord::Base 
    serialize :options, Hash 

    def to_xml(*args) 
    super do |xml| 
     # Hash#to_xml is unaware that the builder is in the middle of building 
     # XML output, so we tell it to skip the <?xml...?> instruction. We also 
     # tell it to use <options> as its root element name rather than <hash>. 
     options.to_xml(:builder => xml, :skip_instruct => true, :root => "options") 
    end 
    end 

    # ... 
end 
+0

我現在正在使用類似的方法。請參閱我編輯的原始問題。由於我不清楚我會爲你的答案投票+1。在你的解決方案中,你需要添加:除了忽略'選項'的參數。否則,最終在串行化的XML字符串中會出現兩個「選項」字段。 – 2010-02-05 22:51:21