Ruby on rails 在带有字符串数组的散列上创建xml失败,因为并非所有元素都响应xml

Ruby on rails 在带有字符串数组的散列上创建xml失败,因为并非所有元素都响应xml,ruby-on-rails,ruby,jruby,Ruby On Rails,Ruby,Jruby,在带有字符串数组的散列上创建xml失败,因为并非所有元素都响应xml >>r={"records"=>["001","002"]} => {"records"=>["001", "002"]} >>r.to_xml RuntimeError: Not all elements respond to to_xml from /jruby/../1.8/gems/activesupport2.3.9/lib/active_support/

在带有字符串数组的散列上创建xml失败,因为并非所有元素都响应xml

 >>r={"records"=>["001","002"]}

 => {"records"=>["001", "002"]}

 >>r.to_xml

 RuntimeError: Not all elements respond
 to to_xml   from
/jruby/../1.8/gems/activesupport2.3.9/lib/active_support/core_ext/array/conversions.rb:163:in `to_xml'
是否有rails首选的方法来更改Hash.to_xml行为以返回

<records>
 <record>001</record>
 <record>002</record>
</records>

001
002

不,因为
“001”
“002”
不可能知道如何成为
001
。这些字符串就是:字符串。他们不知道它们是在一个数组的散列中使用的,更不用说这些字符串共享一个需要奇点化的键了

你可以这样做:

record = Struct.new(:value) do
  def to_xml
    "<record>#{value}</record>"
  end
end

r = { "records" => [ record.new("001"), record.new("002") ] }
r.to_xml
record=Struct.new(:value)do
def to_xml
“#{value}”
结束
结束
r={“records”=>[record.new(“001”)、record.new(“002”)]}
r、 到xml

或者,使用类似于将xml与数据结构分开的工具。

正如DigitalRoss所说,在Ruby 1.9和ActiveSupport 3中,这似乎是开箱即用的:

ruby-1.9.2-p0 > require 'active_support/all'
 => true 
ruby-1.9.2-p0 > r={"records"=>["001","002"]}
 => {"records"=>["001", "002"]} 
ruby-1.9.2-p0 > puts r.to_xml
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <records type="array">
    <record>001</record>
    <record>002</record>
  </records>
</hash>
这给了你

ruby-1.8.7-head > load 'myexample.rb'
 => true 
ruby-1.8.7-head > r={"records"=>["001","002"]}
 => {"records"=>["001", "002"]} 
ruby-1.8.7-head > puts r.to_xml
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <records type="array">
    <record>001</record>
    <record>002</record>
  </records>
</hash>
ruby-1.8.7-head>加载'myexample.rb'
=>正确
ruby-1.8.7-head>r={“记录”=>[“001”,“002”]}
=>{“记录”=>[“001”,“002”]}
ruby-1.8.7-head>将r.to_xml
001
002

请注意,我的代码不适用于Ruby 1.9和ActiveRecord 3。

您确定这是正确的吗?当我在Rails3上尝试OP的示例案例时,它就像他想要的那样工作,所以我查看了ActiveSupport源代码,发现他的异常出现在Rails2而不是Rails3中。(至少,不是在同一个地方。)无法复制我放弃的异常,但这当然是可能的,因为rails 3完全可以做他想要的。非常好。谢谢您的解决方案也适用于jruby 1.5.2。
ruby-1.8.7-head > load 'myexample.rb'
 => true 
ruby-1.8.7-head > r={"records"=>["001","002"]}
 => {"records"=>["001", "002"]} 
ruby-1.8.7-head > puts r.to_xml
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <records type="array">
    <record>001</record>
    <record>002</record>
  </records>
</hash>