1

我正在尝试构建一个简单的方法,该方法可以从 ruby​​ on rails 中的数据库创建 XML 文件。我觉得我的代码是正确的,但我没有看到 XML 中的所有用户。
我是 RoR 的新手。

这是我的代码:

def create_file     
  @users = User.find(:all)
  file = File.new('dir.xml','w')
  doc = Document.new

  make = Element.new "make"
  @users.each do |y|
    make.add_element "name"
    make.elements["name"].text  = y.name
    make.add_element "description"
    make.elements["description"].text = y.description
  end    

  doc.add_element make

  file.puts doc
  file.close
end

我的 XML 输出:

<make>
 <name>sammy</name><description>samsdescription</description>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
 <name/><description/>
</make>

我不明白为什么没有填充所有字段。为什么只显示一个数据库整体?我真的很感激帮助。

4

2 回答 2

4

You ought to investigate @users.to_xml to see if it is something you could use instead of rolling your own solution. Read more about it in the Rails API docs.

于 2008-11-03T02:09:48.357 回答
2

您的代码中有一个错误。在每次迭代中,您创建一个元素,add_element然后尝试使用 访问该元素Elements#[]。但是当您在其中使用节点名称时,Elements#[]它只返回第一个匹配的节点。因此,您在每次迭代中都创建一个节点,但只更新第一个节点。尝试将代码更改为以下内容:

@users.each do |y|
  name_node = make.add_element "name"
  name_node.text  = y.name
  desc_node = make.add_element "description"
  desc_node.text = y.description
end

By the way, your XML structure is a bit strange. Wouldn't it be more clear if you wrapped every name/description pair inside another node (say, user) and then have many user nodes?

于 2008-11-02T18:33:41.427 回答