Nachshon Schwartz
Nachshon Schwartz

Reputation: 15765

Database-safe Concurrency in ROR

Trying to figure out how concurrency is dealt with in Ruby On Rails.

How do I get a segment of code to lock on lines in the database and force rollbacks when needed?

More specificly, Is there a way to force a certain segment of code to complete totally and if not rollback? I'm looking to add history to transactions in my project and I don't want transactions to commit without the history being saved so if the server falls between the two actions (saving the transaction and saving the history) the database may go into an illegal state.

Upvotes: 5

Views: 219

Answers (2)

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

You want to look at ActiveRecord Transactions and Pessimistic Locking.

Account.transaction do
  account = Account.find(account_id)
  account.lock!

  if account.balance >= 100
    account.balance -= 100
    account.save
  end
end

Upvotes: 5

Ricardo Acras
Ricardo Acras

Reputation: 36244

Yes, you have a way of implementing a transaction in Rails. An example:

YourModel.transaction do
  rec1.save!
  rec2.save!
end

More info here

Upvotes: 1

Related Questions