Today I’m working on my rails project at work as usual, and met with a scenario that needs me to update a model by deleting and saving it in one go. So I learned that there is a way of doing it by using the transaction class method from ActiveRecord.
It is very simple to use, you simply need to place the desired active record functions as a block argument into the transaction method like such:
Account.transaction do balance.save! account.save! end
By using this way, SQL statements will only become permanent if they can all succeed as one atomic action, so it is safe to make a series of active record interactions without worrying that it will fail half way, and left you in an undetermined and hard-to-debug state.