Deserialize ActiveRecord from JSON

…衆ロ難τιáo~ 提交于 2019-12-22 00:03:15

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7879637/deserialize-activerecord-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!