Understanding Active Record Transactions in Rails

Table of contents

Introduction
Hey folks! Today, we’re going to have a simple and brief talk about Active Record transactions in Rails. We won’t dive too deep, but I’ll give you a glimpse of how useful they are.
Active Record transactions ensure that all operations within the transaction block are treated as a single unit. If an error occurs at any point inside the block, the entire transaction is rolled back automatically.
This provides atomicity, meaning either all changes are committed, or none are—ensuring data consistency. No partial updates will occur within a transaction.
Important Notes:
A transaction only rolls back if an exception is raised inside it.
Methods like
update!
andsave!
raise exceptions on failure, making them ideal for transactions.Regular
save
orupdate
won’t trigger a rollback on failure unless an exception is explicitly raised.If you want to rollback a transaction without raising an error that propagates, you can use
raise ActiveRecord::Rollback
.
Simple Example
Let’s take a look at a basic example that demonstrates these concepts:
ActiveRecord::Base.transaction do
user = User.create!(name: "John Doe")
order = Order.create!(user: user, total: 100)
# Simulating an issue
raise ActiveRecord::Rollback if order.total > 50
end
# If an error occurs, both user and order creation will be rolled back.
In this case, if the order.total
exceeds 50
, we manually trigger a rollback using raise ActiveRecord::Rollback
, ensuring that neither the User
nor the Order
is saved to the database.
Conclusion
Using Active Record transactions in Rails is a great way to maintain data integrity. By treating multiple operations as a single unit, we can prevent inconsistent states in our database. Just remember:
Always use
save!
orupdate!
to ensure an exception is raised on failure.If you need to rollback without raising a full-blown error, use
raise ActiveRecord::Rollback
.
This way, your database stays clean and consistent! 🚀
Subscribe to my newsletter
Read articles from Abdelrahman Gamal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
