从JSON反序列化ActiveRecord
我想使用JSON序列化将查询结果保存到redis中并查询它。
将查询结果提供给json非常简单:
JSON.generate(Model.all.collect {|item| item.attributes})
但是我没有找到将其反序列化回ActiveRecord的正确方法。 最直接的方式:
JSON.parse(@json_string).collect {|item| Model.new.from_json(item)}
给我一个错误:
WARNING: Can't mass-assign protected attributes: id
所以id变空了。 我想过只使用OpenStruct代替ActiveRecord,但我相信有更好的方法。
您可以从JSON实例化新对象,然后再分配id。 可能最好为此创建自己的方法:
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.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
如果创建JSON的主机添加了JSON根,则可能必须使用item[1]
而不是item
。