【问题标题】:Rails: restore ActiveRecord object encoded with to_jsonRails:恢复使用 to_json 编码的 ActiveRecord 对象
【发布时间】:2012-07-17 18:23:27
【问题描述】:

我有一个名为 Account 的模型,具有这些关联:

has_many :contracts, :dependent => :destroy
has_many :packages, :dependent => :destroy

accepts_nested_attributes_for :contracts
accepts_nested_attributes_for :packages

在销毁任何 Account 对象之前,我使用 to_json 将其保存在一个文件中:

@account.to_json(:include => [:packages, :contracts])

很好。当我尝试恢复它时会出现问题(在另一个脚本上):

account_data = JSON.parse json
@account = Account.new account_data

这引发了一个异常:

Package(#70193553579560) expected, got Hash(#70193548333800)

为什么会这样?在这种情况下,Rails 不应该接受哈希吗?

在我执行@account.save 之后,我是否必须从哈希中删除合约和包密钥并插入它们?我正在寻找一种更清洁的方法来处理这个问题:)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    查看@account.to_json(:include => [:packages, :contracts]) 的输出。它将关联序列化为 JSON,因此您最终会得到以下内容:

    {"id":10, packages:[{id:5,description:"Package1"}], contracts:[]}
    

    当您尝试重新加载 JSON 时,它实际上是在尝试这样做:

    account.packages = [{id:5,description:"Package1"}]
    

    这不起作用,因为 account.packages 是一个关联,您不能直接使用 Hash 构建它。但是,您可以将 Hash 作为嵌套属性传递:

    account.packages_attributes = [{id:5,description:"Package1"}]
    

    packages_attributes 是由 accepts_nested_attributes_for 类方法定义的方法,您的模型中已有该方法。

    这与to_json 不匹配。但是,ActiveRecord 也有一个 from_json 方法,旨在很好地播放 to_json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 2012-11-13
      相关资源
      最近更新 更多