ActiveRecord: transactions
This course covers ActiveRecord::Base.transaction in application code, for cases where several related writes must succeed or fail together. It tests which ways of leaving a block trigger a rollback: a raised exception rolls back, while a bare return or a falsy value commits. It shows ActiveRecord::Rollback for silent cancellation, nested blocks that join the outer transaction, and requires_new: true with savepoints. It then reads this app's CompleteLessonService and AccountUpdateService line by line and explains why save! and update! matter inside a transaction.
What you'll learn
- ✓How ActiveRecord::Base.transaction makes a group of writes all or nothing
- ✓Why only a raised exception rolls back, while return and falsy values commit
- ✓When to use ActiveRecord::Rollback for a silent, expected cancellation
- ✓How nested transactions join the outer one and what requires_new: true changes
- ✓Why save! and update! decide whether earlier writes in a block are undone
ActiveRecord::Base.transaction: all your writes, or none of them
ActiveRecord migrations: multi-table showed that Rails wraps an ordinary migration's whole change method in one database transaction, so several create_table calls either all land or none do. Nobody wrote that transaction by hand; Rails supplied it. This course covers the same guarantee written…
Read the full lesson free →Curriculum
7 lessonsActiveRecord::Base.transaction: all your writes, or none of them
Wraps several related writes in one ActiveRecord::Base.transaction block so they all become durable together or none do.
What triggers a rollback
Tests three ways to leave a transaction block: a raised exception rolls back, while a bare return commits.
ActiveRecord::Rollback: canceling without raising an error
Shows how ActiveRecord::Rollback undoes every write in the block without propagating an exception to the calling code.
Nested transactions and the requires_new trap
Explains why a nested transaction joins the outer one by default and how requires_new: true adds a savepoint.
Reading this app's CompleteLessonService, line by line
Reads this app's CompleteLessonService line by line and shows its safety depends on where the early return sits.
Why save! matters more inside a transaction than outside one
Shows why plain save and update leave partial writes inside a transaction, and how update! prevents that.
Putting it together: what protects a block of writes
Checks every rule against AccountUpdateService, its RSpec suite and the commit that switched its writes to update!.