2010-02-05 122 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