代码之家  ›  专栏  ›  技术社区  ›  Harish Shetty

ActiveRecord可序列化属性中的XML序列化问题

  •  2
  • Harish Shetty  · 技术社区  · 15 年前

    在我的用户模型中有一个名为options(Hash类型)的序列化字段。选项字段在大多数情况下的行为类似于散列。当我将user对象转换为XML时,“options”字段被序列化为YAML类型而不是散列。

    我通过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>
    

    编辑:

    我通过向xml传递一个块来解决这个问题

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

    我想知道有没有更好的办法。

    1 回复  |  直到 15 年前
        1
  •  2
  •   molf    15 年前

    序列化是用数据库中的YAML完成的。他们没有告诉您的是,它还作为YAML传递给XML序列化程序。最后一个论点 serialize 分配 options 应为类型 Hash .

    to_xml 用你自己的实现。借用原始的xmlbuilder对象并将其传递给 选项

    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