# Convert XML elements to activerecord objects

**URL:** <https://www.ruby-forum.com/t/convert-xml-elements-to-activerecord-objects/113389>\
**Category:** Rails\
**Created:** [August 30, 2007, 4:54pm UTC](https://www.ruby-forum.com/t/convert-xml-elements-to-activerecord-objects/113389 "2007-08-30T16:54:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![johnnybutler7](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8491ac/32.png) [@johnnybutler7](https://www.ruby-forum.com/u/johnnybutler7)\
**Post date:** [August 30, 2007, 4:54pm UTC](https://www.ruby-forum.com/t/convert-xml-elements-to-activerecord-objects/113389/1 "2007-08-30T16:54:45Z")

</div>

hi,

I wonder if this is possible as i find myself repeating code which is  
not a good sign, Kent Becks “3 strikes and your out” rule.

I am reading in a bunch of xml objects using REXML. So for instance a  
couple are below but there could be a lot more.

Building 1 Client Name

Each element above corresponds to a model in the database so i need a  
generic method which will loop through all the elements in the XML file  
and add them to the corresponding model table in the database if they  
dont already exist and then return the object so it can be updated to  
the parent model.

example

for element in element.elements  
#i need to get the model in the tempmodel object from the xml elements  
name?  
#element.name will return Client for the 1st xml element  
tempmodel = element.name

#the below would return a Client object Client.find\_by\_name(Building  
1)  
object = tempmodel.find\_by\_name(element.text)  
if object.nil?  
object = tempmodel.new(:name =\> element.text)  
object.save  
end

“#{e.downcase}=”.to\_sym

#the below would turn Client into client as thats the method  
project.client  
tempmethod = tempmodel.downcase

project.tempmethod = object  
project.save

end

Is the above possible and if so can anyone offer some advice or  
examples, im searching the API but cant find what i am looking for.

JB

---

<div class="post-metadata">

**Author:** ![johnnybutler7](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8491ac/32.png) [@johnnybutler7](https://www.ruby-forum.com/u/johnnybutler7)\
**Post date:** [August 31, 2007, 9:45pm UTC](https://www.ruby-forum.com/t/convert-xml-elements-to-activerecord-objects/113389/2 "2007-08-31T21:45:47Z")

</div>

An the naswer is:

mod = element.name.camelize.constantize  
mod.find\_by\_name(“value”)

attname = element.name.underscore  
project.update\_attribute(attname, object)

JB
