note
Rails 6 adds insert_all, insert_all!, upsert_all for bulk insertion
insert_all(attributes, returning: nil, unique_by: nil)
This method can be used to insert multiple records with a single SQL INSERT statement. The method simply skips ActiveRecord callbacks or validations. It accepts array of hashes, where every hash determines the attributes for a single record or row.
insert_all!(attributes, returning: nil)
This method works same as that of insert_all but in addition to that it raises ActiveRecord::RecordNotUnique if any record violates a unique index on the table.
upsert_all(attributes, returning: nil, unique_by: nil)
It updates the records if they exist or simply inserts them into database with a single SQL INSERT statement.
NOTE:
- Can't use reference: i.e. use
user_id
instead of user
- Must provide value for all fields, e.g. created_at, updated_at