开发者

rails inverting to_xml and getting the original model

I did this:

[User.first, User.last开发者_C百科].to_xml

and got this:

<users type="array">
   <user>
     <created-at type="datetime">2010-03-16T06:40:51Z</created-at>
     <id type="integer">3</id>
     <password-hash></password-hash>
     <salt></salt>
     <updated-at type="datetime">2010-03-16T06:40:51Z</updated-at>
     <username nil="true"></username>
   </user>
   <user>
     <created-at type="datetime">2010-03-23T03:58:15Z</created-at>
     <id type="integer">7</id>
     <password-hash></password-hash>
     <salt></salt>
     <tutorial-state nil="true"></tutorial-state>
     <updated-at type="datetime">2010-03-23T03:58:15Z</updated-at>
     <username nil="true"></username>
   </user>
</users>

How can I take that string of xml and invert it to get the original activerecord objects back?


Try this:

Model object xml:

xml = User.first.to_xml
User.new(Hash.from_xml(xml))

Array of model xml:

xml = User.all.to_xml
users = (Hash.from_xml(xml)["users"] || []).collect{|attr| User.new(attr)}


I do know that you can do this on individual users; doing it on an array will require your own bit of XML parsing.

user = User.new
user.from_xml '<user><id type="integer">1</id></user>'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜