Question

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.

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top