Rails: restoring ActiveRecord objects from a JSON array

I have a JSON array with ActiveRecord objects. These objects can be restored using the from_json method that every AR object has. However, only one object can be restored using from_json.

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

0


source to share


1 answer


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)

      

which is best for you.

Both of these methods return a Ruby data structure that matches the json structure. So, if you have a json array of obejcts, after JSON.load or JSON.parse you will get an array of Ruby hashes. You shouldn't have any problems to manipulate such a structure.

+6


source







All Articles