【问题标题】:How to restore the class of associations from an ActiveModel object serialized into JSON?如何从序列化为 JSON 的 ActiveModel 对象恢复关联类?
【发布时间】:2012-02-29 10:54:25
【问题描述】:

我有一个包含 ActiveModel 的类,它需要有一些“关联”,如下所示:

a      = ActiveModelClass.new
a.user = User.find(1)

我只是为此使用 attr_accessor:

attr_accessor :user

### Elsewhere ###

a.user.name # => "Kevin"

到目前为止一切顺利。但是现在我想把它序列化成 JSON:

json = a.to_json
b    = ActiveModelClass.new(ActiveSupport::JSON.decode(json))

但是现在,用户是一个哈希:

b.user.class # => Hash

我怎样才能干净地将这些“关联”恢复为它们原来的类的对象?

【问题讨论】:

    标签: ruby-on-rails ruby json activerecord activemodel


    【解决方案1】:

    我有点困惑:我感觉你已经把你的例子抽象到了难以理解的地步。你有这样的东西吗?

    b.user 
    => {:name => "Kevin", :email => "kev@foo.foo"}
    

    ?

    如果是这样,您只需将其传递给 .new 或 .create 方法,就可以从这个散列中创建一个用户对象:

    user = User.create(b.user) 
    

    然后您可以使用此用户对象做您想做的事情,包括将 b.user 设置为等于它。

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 2016-05-12
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 2017-11-25
      • 1970-01-01
      • 2019-05-09
      相关资源
      最近更新 更多