user1735921
user1735921

Reputation: 1379

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

Suppose I have these models in rails.

ParentObject Model

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

ChildObject Model

class ChildObject < ParentObject
  include Mongoid::Document

  belongs_to :parent_object

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

Now to save data I use this code.

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

So that is how data is saved. Now I want to save data using a hash without using the .new method , i.e. without initializing the object. How can that be done? I just want to store from a hash which has values for child object as well as parent object. What would be the format for that hash? I mean I don't even have a parent_object_id

My primary object is to batch insert the data into parent and child object no matter how.

Upvotes: 1

Views: 460

Answers (1)

Joshua Azemoh
Joshua Azemoh

Reputation: 179

The hash should contain an array of child_objects_attributes hashes

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

With this calling ParentObject.create(hash) would create both objects and their associations.

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

Upvotes: 1

Related Questions