# Reconstructing model objects from XML

**URL:** <https://www.ruby-forum.com/t/reconstructing-model-objects-from-xml/113170>\
**Category:** Rails\
**Created:** [August 28, 2007, 11:17am UTC](https://www.ruby-forum.com/t/reconstructing-model-objects-from-xml/113170 "2007-08-28T11:17:40Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Olly\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/eb8c5e/32.png) [@Olly\_L](https://www.ruby-forum.com/u/Olly_L)\
**Post date:** [August 28, 2007, 11:17am UTC](https://www.ruby-forum.com/t/reconstructing-model-objects-from-xml/113170/1 "2007-08-28T11:17:40Z")

</div>

Hi

I’m using to\_xml to provide XML export model objects. I’m looking for  
a simple solution to implement the reverse, so that I can reconstruct  
the model objects from the XML.

Using Hash.from\_xml I can parse the XML into a Hash and pass this into  
the initializer:

```
m = Model.new(hash)

```

Whilst this works fine for simple models it doesn’t (seemingly) work  
with relationships. Take the following example:

```
class Account
  has_many :users
end

```

The XML produced by to\_xml is:

```
<account>
  <id>1</id>
  <users>
    <user>
      <id>1</1>
    </user>
  </users>
</account>

```

Calling Account.new(hash) results in  
“ActiveRecord::AssociationTypeMismatch: User expected, got Array”,  
which is to be expected because the initialize method doesn’t  
configure relationships in this way (I don’t think).

Does anyone have a proper solution for this problem, perhaps by  
extending ActiveRecord, or is it just a matter of manually  
reconstructing each of the relationships?

Thanks in advance.
