Nils
Nils

Reputation: 13777

Rails: Reconstructing ActiveRecord Objects from a JSON array

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.

Upvotes: 0

Views: 6177

Answers (1)

Milan Novota
Milan Novota

Reputation: 15598

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.

Upvotes: 6

Related Questions