Saving multiple objects in a single call in rails

后端 未结 6 479
無奈伤痛
無奈伤痛 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条回答
  •  一生所求
    2020-12-12 13:59

    insert_all (Rails 6+)

    Rails 6 introduced a new method insert_all, which inserts multiple records into the database in a single SQL INSERT statement.

    Also, this method does not instantiate any models and does not call Active Record callbacks or validations.

    So,

    Foo.insert_all([
      { first_name: 'Jamie' },
      { first_name: 'Jeremy' }
    ])
    

    it is significantly more efficient than

    Foo.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
    

    if all you want to do is to insert new records.

提交回复
热议问题