The create_from_xml method can also be used to read in XML that contains markup
for more than one model record. The following code is a simple script that reads in an XML file
CHAPTER 7 ?– WORKING WITH LEGACY SCHEMA 183
that contains data for multiple accounts. In our data, it assumed that some records do not yet
have a primary key, while others do. Therefore, if the primary key in the XML is not nil, the
script will attempt to find the corresponding record and update it. If the record is not found,
or if the primary key was nil, then the record will be created.
accounts_xml_string = File.read("accounts.xml")
accounts = Hash.create_from_xml(accounts_xml_string)
accounts.each do |account|
if account["id"].nil? || !Account.exists?(account["id"])
Accounts.create(account)
else
Accounts.find(account["id"]).update_attributes(account)
end
end
While, the preceding code may not be considered production ready (it does not include
any error checking or reporting), you can see that in a few simple lines, we can import an entire
XML file of accounts into our database, updating records that already exist.
Pages:
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418