I am attempting to build a simple method that creates an XML file from a database in ruby on rails. I feel like my code is right but I am not seeing all of the users in the XML.
I am a complete newbie to RoR.
Here's my code:
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
And my XML output:
<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>
I don't get why all the fields aren't populated. Why is just one of the database entires showing up? I really appreciate the help.
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 .
There's a bug in your code. In each iteration you create an element with add_element
and then try to access that element with Elements#[]
. But when you use a node name in Elements#[]
it returns only the first matching node. So you are creating a node in every iteration but updating only the first one. Try to change the code to the following:
@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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.