从JSON反序列化ActiveRecord [英] Deserialize ActiveRecord from JSON

查看:121
本文介绍了从JSON反序列化ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆