views:

1613

answers:

2

I have a JSON array with ActiveRecord objects. These objects can be reconstructed using the from_json method, which every AR object has. However with from_json it's only possible to reconstruct one single object.

To process an array, I could of course just extract substrings from the JSON array and create every object from it's own substring in a loop or so. However I'm wondering if there is a better way to do this, without string manipulation involved.

+4  A: 

I would do

sudo gem install json

After that just

require "json"

and do

JSON.load(array_of_ar_json_representation)

or

JSON.parse(array_of_ar_json_representation)

what fits better for you.

Both of these methods return Ruby data structure that corresponds to the json structure. So, if you have a json array of obejcts, after JSON.load or JSON.parse you'll get Ruby array of hashes. You should't have any problems to manipulate this kind of structure.

Milan Novota
A: 

Thanks for the answer!

I think the original AR object can be reproduced by passing the hash to the constructor of it, so there would be no need to use from_json..

Nils