Wasasando

SQL efficient bulk insert/upsert landed in Rails codebase

[https://github.com/rails/rails/pull/35077](https://github.com/rails/rails/pull/35077) was finally merged. You can find more details in my [blog post](https://medium.com/@retrorubies/upcoming-rails-6-bulk-insert-upsert-feature-2d642419557d).

Now you can do (with PostgreSQL adapter):

```ruby
now = Time.now
bulk_data = 1000.times.map {|t| {slug: "slug-#{t}", post: "text #{t}", created_at: now, updated_at: now}}
Post.insert_all!(bulk_data)
```

Boom, done in 1 query (locally under 0.4s).

You can even upsert if you have unique index on slug column:

```ruby
now = Time.now
bulk_data = 1000.times.map {|t| {slug: "slug-#{t}", post: "text #{t}", created_at: now, updated_at: now}}
Post.upsert_all(bulk_data, unique_by: { columns: [:slug]})

```

Exit mobile version