Unless I’m missing something, the default rails from_json and from_xml methods don’t work with data that have associated objects. Here are routines that work for some simple examples I’ve tested. I placed this code in vendor/rails/activerecord/lib/active_record/base.rb within the ActiveRecord::Base class, but there might be a better place to put it.
Also available on pastie.
Example usage, using the to_xml example:
Note: this only works if the classes of the nested objects are canonically named. If any of your associations use the :class_name option, you will probably need to update this code to discover the proper class names.
I just wrote this a couple hours ago, so please consider this to be an alpha version.
3 Comments, Comment or Ping
Pete McKinstry
Thanks Matt. It was nice to find that i wasn’t alone w/ the weird from_xml behavior. ‘Preciate the sample code too.
Aug 11th, 2008
Matt Pulver
I knew I wasn’t the only one.
I’ve since generalized the code and tested it more thoroughly. The upgrade is here.
If anyone finds any bugs, send me a simple test case and I will try to fix it.
Aug 11th, 2008
Reply to “ActiveRecord from_json and from_xml”