ruby-on-rails - 从 JSON 初始化 Rails 模型 - 如何初始化子关联?

标签 ruby-on-rails activerecord serialization

我正在生成要存储在rails中的数据。我已将数据导出为序列化 JSON 字符串。

如何根据该字符串自动构建新对象及其子关联? Model.new(json_string) 抛出错误,因为子项是哈希值并且未初始化。循环遍历每个对象并初始化子对象是唯一的选择吗?我觉得这里可能有一些我不知道的魔法。

示例:

Child belongs_to :parent
Parent has_many :children

json_string = "{
  attribute1:"foo", 
  attribute2:"bar",
  children: [
    {attribute1:"foo"},
    {attribute1:"foo"}
    ]}"

Parent.new(json_string)

ActiveRecord::AssociationTypeMismatch: Child(#79652130) expected, got Hash(#69570820)

有没有办法自动从我的序列化对象初始化新的子对象?真正的问题包括三个 child 级别。

最佳答案

使用 children= 不起作用,因为具有许多关联的 setter 需要模型实例数组,并且不打算用于从哈希创建关联记录。

而是使用 nested attributes :

class Parent
  has_many :children
  accepts_nested_attributes_for :children
end

这将允许您通过将属性作为 children_attributes 传递来创建子项:

json_string = '{
  "attribute1":"foo", 
  "attribute2":"bar",
  "children_attributes": [
    { "attribute1":"foo"},
    { "attribute1:""foo"}
  ]
 }'

Parent.new(JSON.parse(json_string))

关于ruby-on-rails - 从 JSON 初始化 Rails 模型 - 如何初始化子关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42377161/

相关文章:

jquery - 在 Rails 中使用 jquery

mysql - save()后自动增量属性始终为空

c# - SQLite.net 中的可序列化数据类型

ruby-on-rails - Heroku 上的延迟作业与 RabbitMQ 有何优缺点?

ruby-on-rails - 通过 http 而不是文件系统导入 SASS 部分

mysql - Activerecord:将 ruby​​ 方法转移到 sql-land

mysql - 查找关联模型中日期范围内的差距 | Rails 上的 Ruby

c++ - 是否可以卡住和转储程序状态?

java - 使用 Jackson 反序列化 java.utils.logging.Level 类返回 null

javascript - 从多个数组构建自定义 JSON 数组