Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple records into database

How can I insert multiple records into a database using rails syntax.

INSERT INTO users (email,name) VALUES ('[email protected]','a'),('[email protected]','b'),
                                      ('[email protected]','c');

This is how we do it in MySQL. How is this done in Rails?

like image 925
Amal Kumar S Avatar asked Apr 27 '11 11:04

Amal Kumar S


1 Answers

While you cannot get the exact SQL that you have there, you can insert multiple records by passing create or new on an array of hashes:

new_records = [
  {:column => 'value', :column2 => 'value'}, 
  {:column => 'value', :column2 => 'value'}
]

MyModel.create(new_records)
like image 104
Peter Brown Avatar answered Nov 10 '22 10:11

Peter Brown