Rails 6 adds after_save_commit


Rails had provided an after_commit callback for ActiveRecord objects. It is called after a record has been created, updated or destroyed.

We can also use below shortcut of after_commit when creating, updating or destroying a record respectively:

  • after_create_commit
  • after_update_commit
  • after_destroy_commit

Rails has a separate shortcut for create and update, but a comman callback for creating or updating a record was missing.

Rails 6 introduces a shortcut for after_commit :hook, on: [:create, :update]

Before Rails 6:

class User < ApplicationRecord
  after_commit :log_user_saved, on: [:create, :update]

  private

    def log_user_saved
      puts "User saved successfully."
    end
end

# Create user
@user = User.create
=> User saved successfully.

@user.save
=> User saved successfully.

In Rails 6:

With the introduction of after_save_commit the above example can be changed to below:

class User < ApplicationRecord
  after_save_commit :log_user_saved

  private

    def log_user_saved
      puts "User saved successfully."
    end
end

# Create user
@user = User.create
=> User saved successfully.

@user.save
=> User saved successfully.