Skip to main content

Atomic Updates And Performance with ActiveRecord Transactions Discussion

General • Asked by Chris Oliver

sally.transfer(bob, 10000), it is not rollback!

why?

class Account < ApplicationRecord
validates :balance, numericality:{ greater_than: 0}

def withdraw(amount)
update(balance: balance - amount)
end

def deposit(amount)
update(balance: balance + amount)
end

def transfer(recipient, amount)
transaction do
withdraw(amount)
recipient.deposit(amount)
end
end
end

must use save! or update!

def withdraw(amount)
update!(balance: balance - amount)
end

def deposit(amount)
update!(balance: balance + amount)
end


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.