Improving Rails Migrations Using bulk: true

When working with Rails migrations, performance isn’t usually the first thing that comes to mind—until your schema starts getting big or you’re deploying changes to production environments with large databases. Fortunately, Rails provides a simple way to optimize schema changes: the bulk: true option.

What is bulk: true in Rails Migrations?

Introduced in Rails 5.2, the bulk: true flag can be passed to methods like change_table or create_table to group multiple schema changes into a single SQL statement, when supported by your database.

This approach reduces the number of separate ALTER TABLE calls, which not only improves performance but can also prevent potential locking or downtime issues in large tables.

Without bulk: true

1
2
3
4
5
6
7
8
class AddFieldsToUsers < ActiveRecord::Migration[7.0]
  def change
    change_table :users do |t|
      t.string :nickname
      t.boolean :admin, default: false
    end
  end
end

In this example, Rails will execute two separate ALTER TABLE statements—one for nickname and another for admin.

With bulk: true

1
2
3
4
5
6
7
8
class AddFieldsToUsers < ActiveRecord::Migration[7.0]
  def change
    change_table :users, bulk: true do |t|
      t.string :nickname
      t.boolean :admin, default: false
    end
  end
end

Here, Rails will combine both column additions into a single ALTER TABLE statement, reducing overhead and speeding up the migration.

Things to Keep in Mind

When Should You Use bulk: true?

You should use bulk: true whenever you’re adding multiple columns to the same table in a single migration. It’s a small change in code that can lead to faster, safer migrations and cleaner schema logs—especially helpful in large applications or continuous deployment environments.

Using bulk: true is a subtle yet powerful optimization that many developers overlook. It doesn’t add complexity to your migration, but it can significantly reduce downtime and improve deploy times.