Search code examples
ruby-on-railsjsondeserializationmass-assignment

Deserialize ActiveRecord from JSON


I would like to save query result into redis using JSON serialization and query it back.

Getting query results to json is pretty easy:

JSON.generate(Model.all.collect {|item| item.attributes})

However I did not find a proper way to deserialize it back to ActiveRecord. The most straight-forward way:

JSON.parse(@json_string).collect {|item| Model.new.from_json(item)}

Gives me an error:

WARNING: Can't mass-assign protected attributes: id

So id gets empty. I thought of just using OpenStruct for the views instead of ActiveRecord but I am sure there is a better way.


Solution

  • You could instantiate the new object from JSON and then assign the id afterwards. Probably best to create your own method for this:

    class Model
      def self.from_json_with_id(params = {})
        params = JSON.parse(params)
        model = new(params.reject {|k,v| k == "id"})
        model.id = params["id"]
        model
      end
    end
    

    Or maybe just override the from_json() method.