Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in way to convert xml to an ActiveRecord Object in Rails 3?

In Rails 3, is there a way to produce an ActiveRecord object from xml in a controller without writing code yourself to explicitly parse it? Say for example, could a controller receive xml like

<user>
 <first_name>Bob</first_name>
 <last_name>Smith</last_name>
</user>

and have it produce a proper User object similar to User.new(params[:user])? This is for an api.

like image 913
salmonthefish Avatar asked Apr 20 '11 15:04

salmonthefish


2 Answers

Yes, you can do it like this:

@user = User.new
@user.from_xml(xml_data)

Update

On overriding you can do something like this:

#user.rb
def from_xml(xml_data)
  book = Book.new
  book.from_xml(extract_xml_from(xml_data))
  self.books << book
  super(xml_data)
  save
  book.save
end

Please note that the most important line in the overriding is the super(xml_data) which will take care on calling the original from_xml(xml_data) of the ActiveRecord model. So you can customize the rest as needed, but this line is neede if you want to get the original functionality as well. Let me know if something is not clear.

like image 184
dombesz Avatar answered Sep 29 '22 22:09

dombesz


I've created a gem, xml_active that might help you with this without having to write a lot of code. You can check it out at https://rubygems.org/gems/xml_active.

To get it to create one object with associations just do the following:

book = Book.one_from_xml xml_data

You can also get xml_active to create many objects from xml along with associations. There are more features but probably not in the scope of this answer. You can check them out on the home page for the gem.

UPDATE

xml_active has now been officially retired and development is now focused on data_active (see https://github.com/michael-harrison/data_active) which has the functionality of xml_active but in future releases I will be working to support other formats

like image 45
Michael Harrison Avatar answered Sep 29 '22 22:09

Michael Harrison