|
| 1 | +# Batch Update |
| 2 | + |
| 3 | +Update multiple records with different values in an optimized number of queries. |
| 4 | + |
| 5 | +This differs from [activerecord-import](https://github.com/zdennis/activerecord-import) because the latter issues a `INSERT ... ON DUPLICATE KEY UPDATE` statement which re-inserts the record if it happens to have been deleted in a other thread. |
| 6 | + |
| 7 | +## Usage |
| 8 | +Include in your Gemfile: `gem 'batch_update'` |
| 9 | + |
| 10 | +```ruby |
| 11 | +cat1 = Cat.create!(name: 'Felix', birthday: '1990-03-13') |
| 12 | +cat2 = Cat.create!(name: 'Garfield', birthday: '1978-06-19') |
| 13 | +cat3 = Cat.create!(name: 'Daisy', birthday: '1970-01-01') |
| 14 | + |
| 15 | +cat1.birthday = '2024-01-01' |
| 16 | +cat2.birthday = '2024-06-06' |
| 17 | +cat3.birthday = '1900-01-01' |
| 18 | + |
| 19 | +Cat.batch_update([cat1, cat2, cat3]) # issues a single SQL query |
| 20 | +``` |
| 21 | + |
| 22 | +The SQL query looks like the following: |
| 23 | +```SQL |
| 24 | +WITH "batch_updates" (birthday, id) AS ( |
| 25 | + VALUES (CAST('2024-01-01' AS date), CAST(1 AS INTEGER)), ('2024-06-06', 2), ('1900-01-01', 3), |
| 26 | +) |
| 27 | +UPDATE "cats" |
| 28 | +SET |
| 29 | + "birthday" = "batch_updates"."birthday" |
| 30 | +FROM "batch_updates" |
| 31 | +WHERE |
| 32 | + "cats"."id" = "batch_updates"."id" |
| 33 | +``` |
| 34 | + |
| 35 | +## Advanced usage |
| 36 | +Specify which columns to update (all columns are included by default): |
| 37 | +```ruby |
| 38 | +cat1.name = 'Lilly' |
| 39 | +cat1.birthday = '2024-01-01' |
| 40 | +cat2.birthday = '2023-06-06' |
| 41 | +Cat.batch_update([cat1, cat2], columns: %i[birthday]) |
| 42 | +``` |
| 43 | + |
| 44 | +Ignore model validations (all validations run by default): |
| 45 | +```ruby |
| 46 | +cat1.name = '' |
| 47 | +cat2.name = '' |
| 48 | +Cat.batch_update([cat1, cat2], validate: false) |
| 49 | +``` |
| 50 | + |
| 51 | +Specify a different batch size (100 by default): |
| 52 | +``` |
| 53 | +Cat.batch_update(cats, batch_size: 1000) |
| 54 | +``` |
| 55 | + |
| 56 | +## License |
| 57 | +MIT |
0 commit comments