Skip to main content

Subscribe to GoRails to get access to this episode and all other pro episodes, and new awesome content every month.

Subscribe Now
Only $19/month

Unlimited access. Cancel anytime.

26 Atomic Updates And Performance with ActiveRecord Transactions

Episode 171 · February 6, 2017

Learn how to use ActiveRecord Transactions to create atomic updates across multiple records and to improve the speed of bulk operations

ActiveRecord


Transcripts

Subscribe or login to view the transcript for this episode.

Discussion


Gravatar

Gravatar

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

Gravatar

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.