【问题标题】:Initializing Rails model from JSON - how to initialize child associations?从 JSON 初始化 Rails 模型 - 如何初始化子关联?
【发布时间】:2017-02-21 20:19:19
【问题描述】:

我正在生成要存储在 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)

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

【问题讨论】:

    标签: ruby-on-rails activerecord serialization


    【解决方案1】:

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

    改为使用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))
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找nested_attributes http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

      #Parent.rb
      
      accepts_nested_attributes_for :children
      

      您必须将 json 转换为具有一个名为 children_attributes 的键(其值与子数组相同)才能生效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        相关资源
        最近更新 更多