从JSON反序列化ActiveRecord [英] Deserialize ActiveRecord from JSON
问题描述
我想使用JSON序列化将查询结果保存到redis中,并进行查询.
I would like to save query result into redis using JSON serialization and query it back.
将查询结果获取到json很简单:
Getting query results to json is pretty easy:
JSON.generate(Model.all.collect {|item| item.attributes})
但是,我找不到将其反序列化回ActiveRecord的正确方法.最简单的方法:
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
因此,id为空.我想到了只对视图使用OpenStruct而不是ActiveRecord,但是我相信有更好的方法.
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.
推荐答案
您可以从JSON实例化新对象,然后再分配ID.最好为此创建自己的方法:
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
或者只是重写from_json()
方法.
这篇关于从JSON反序列化ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!