Use Transactions
Basic Transaction
User.transaction do
user = User.create!(name: "John", email: "john@example.com")
Profile.create!(user_id: user.id.not_nil!, bio: "Hello")
end
# Both records created, or neitherAutomatic Rollback on Error
User.transaction do
user = User.create!(name: "John", email: "john@example.com")
raise "Something went wrong!" # Triggers rollback
Profile.create!(user_id: user.id.not_nil!, bio: "Hello")
end
# Neither record is createdHandle Transaction Errors
Transfer Between Records
Create Related Records
Nested Operations
Manual Rollback
Transaction with Return Value
Cleanup Operations
Verify Transaction Behavior
Related
Last updated
Was this helpful?