1

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.

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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?

1 Comment

Yeah, there isn't much use to this right now, i am just playing around to try and learn it. Thanks a lot for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.