Last active
December 17, 2017 10:45
-
-
Save StevenJL/299b601c776f915aeeb339477524c58c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # When creating a lot of records from an array of hashes | |
| new_users = [ | |
| {name: "Teemo", email: "[email protected]"}, | |
| {name: "Heim", email: "[email protected]"}, | |
| {name: "Annie", email: "[email protected]" }, | |
| ... | |
| {name: "Volli", email: "[email protected]" }, | |
| ] | |
| # Do not create each one individually as it results in one query, per record. | |
| new_users.each do |user_hash| | |
| User.create(user_hash) | |
| end | |
| # INSERT INTO users (name, email) VALUES ('Teemo', '[email protected]'); | |
| # INSERT INTO users (name, email) VALUES ('Heim', '[email protected]'); | |
| # INSERT INTO users (name, email) VALUES ('Annie', '[email protected]'); | |
| # ... | |
| # INSERT INTO users (name, email) VALUES ('Volli', '[email protected]'); | |
| # Instead, pass the array into ActiveRecord::Base#create, which will create | |
| # all the records in one query if the database supports this feature. | |
| User.create(new_users) | |
| # INSERT INTO users (name, email) | |
| # VALUES | |
| # ('Teemo', '[email protected]'), | |
| # ('Heim', '[email protected]'), | |
| # ('Annie', '[email protected]'), | |
| # .... | |
| # ('Volli', '[email protected]'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment