Built-in way to convert xml to ActiveRecord object in Rails 3?

Is there a way in Rails 3 to create an ActiveRecord object from xml in the controller without writing code yourself to explicitly parse it? Say for example if the controller can get xml, for example

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

and create a corresponding User object like User.new (params [: user])? This is for api.

+5
source share
2 answers

Yes, you can do it like this:

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

Update

When 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

, - super(xml_data), from_xml(xml_data) ActiveRecord. , , , . , - .

+6

gem, xml_active, . https://rubygems.org/gems/xml_active.

, :

book = Book.one_from_xml xml_data

xml_active xml . , , , . .

xml_active , data_active (. https://github.com/michael-harrison/data_active), xml_active,

+2

All Articles