Deserialize ActiveRecord from JSON
Asked Answered
L

2

1

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.

Leitao answered 24/10, 2011 at 17:49 Comment(0)
P
8

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.

Positronium answered 18/6, 2012 at 10:55 Comment(2)
Though I am suprised there is no built in support for this. This sounds good. ThanksLeitao
Just a heads up, I was winging this. You might want to use allocate instead of new if you want ActiveRecord to realize it's not a new object in the databasePositronium
T
1

Why not like this:

JSON.parse(@json_string).each do |item|
     item.delete(:id) # I tested it in my case it also works without this line
     object=Model.create(item)
end

If the host that created the JSON adds a JSON root you might have to use item[1] instead of item.

Toadstool answered 24/10, 2011 at 18:16 Comment(1)
The json items came from the database in the first place. Using model.create will attempt to create the item in the database and will fail since the item already exists.Leitao

© 2022 - 2024 — McMap. All rights reserved.