Vitalii Zdanovskyi
Vitalii Zdanovskyi

Reputation: 113

Lock model for reading

In an ActiveRecord transaction, I need some way to lock the record/table for reading, so the user was not able to select from this table, while the transaction being executed.

Basically, I need something like this

System.transaction do
  s = System.first
  # Something to lock the table or selected record for reading
  s.update_attributes(some_params)
end

Does anyone have an idea on how to do that?

Upvotes: 1

Views: 775

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54674

It seems you are looking for Pessimistic Locking. You can use the lock method like a scope. Additionally, you should use the bang-version update_attributes! in order to raise an exception when things go wrong.

System.transaction do
  s = System.lock.first
  s.update_attributes!(some_params)
end

Upvotes: 1

Related Questions