Saving multiple objects in a single call in rails

后端 未结 6 483
無奈伤痛
無奈伤痛 2020-12-12 13:25

I have a method in rails that is doing something like this:

a = Foo.new(\"bar\")
a.save

b = Foo.new(\"baz\")
b.save

...
x = Foo.new(\"123\", :parent_id =&g         


        
6条回答
  •  Happy的楠姐
    2020-12-12 13:51

    You might try using Foo.create instead of Foo.new. Create "Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not."

    You can create multiple objects like this:

    # Create an Array of new objects
      parents = Foo.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
    

    Then, for each parent, you can also use create to add to its association:

    parents.each do |parent|
      parent.children.create (:child_name => 'abc')
    end
    

    I recommend reading both the ActiveRecord documentation and the Rails Guides on ActiveRecord query interface and ActiveRecord associations. The latter contains a guide of all the methods a class gains when you declare an association.

提交回复
热议问题