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.
There’s a bug in your code. In each iteration you create an element with
add_elementand then try to access that element withElements#[]. But when you use a node name inElements#[]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: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?