如何在 Rails Mongoid 中不使用 .new(不初始化对象)直接存储具有 has_many 关系的模型散列?

How to directly store a hash of model with has_many relationship without using .new (without initializing object) in Rails Mongoid?

假设我在 rails 中有这些模型。

父对象模型

class ParentObject
  include Mongoid::Document
  has_many :child_objects, autosave: true, dependent: :destroy
  accepts_nested_attributes_for :child_objects

  field :p_test_field, type: String
  field :p_test_field_two, type: String
end

子对象模型

class ChildObject < ParentObject
  include Mongoid::Document

  belongs_to :parent_object

  field :c_test_field, type: String
  field :c_test_field_two, type: String
end

现在我使用这段代码来保存数据。

@parent_object = ParentObject.new(parent_object_params)
@parent_object.child_objects_attributes = {"0" => {:c_test_field => "test2"}}
@parent_object.save

这就是数据保存的方式。现在我想使用散列保存数据而不使用 .new 方法,即不初始化对象。那怎么办?我只想从一个散列中存储,该散列具有子对象和父对象的值。该散列的格式是什么?我的意思是我什至没有 parent_object_id

我的主要目标是无论如何都将数据批量插入到父子对象中。

散列应包含 child_objects_attributes 个散列数组

{
  :p_test_field => "attr test one",
  :p_test_field_two => "attr test two",
  ...
  :child_objects_attributes => [
    { :c_test_field => "test 1" }
  ]
}

通过此调用 ParentObject.create(hash) 将创建对象及其关联。

https://mongoid.github.io/en/mongoid/docs/nested_attributes.html