Rails 求教下 一个 model 被转成 json 后 如何再从 json 恢复成 model 对象

Edmodo-Luo · January 04, 2021 · Last by kevinyu replied at January 05, 2021 · 709 hits

刚写 ruby 不久,如题,求教社区大神有没有什么靠谱的方法

1 Floor has deleted

object.to_json 之后返回的 json 信息没有 class 的信息,无法恢复。

除非,你把 class 信息带进去:

class Company
  def to_json_with_class
    self.attributes.merge(klass: self.class.to_s).to_json
  end
end
  1. 转成 json

    json = company.to_json_with_class
    
  2. 从 json 转成 object

    attrs = JSON.parse(json)
    object = attrs.delete('klass').constantize.new(attrs)
    

X-Y 问题,你想要做什么?

https://coolshell.cn/articles/10804.html

这是一个奇怪的需求。我怀疑你把问题想偏了。。。说出你的“原始需求”应该更有帮助

Model.new(JSON.parse(json))

是不是把对象转成 json 存到 redis 现在取出来恢复呀😂

You need to Sign in before reply, if you don't have an account, please Sign up first.