Convert XML elements to activerecord objects

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

An the naswer is:

mod = element.name.camelize.constantize
mod.find_by_name(“value”)

attname = element.name.underscore
project.update_attribute(attname, object)

JB

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs