Jaydip Pansuriya
Jaydip Pansuriya

Reputation: 214

When is a lock released on an object in Rails?

I have a function in a model class, and inside that function, I have the following code:

def myfun
  .... 
  self.lock!
  self.name = "hi" 
  .... 
  .... 
 end

So, in the above case, when will the lock be released from the object?

Note: I am not wrapping this code in a transaction block.

Upvotes: 3

Views: 1777

Answers (2)

Lam Phan
Lam Phan

Reputation: 3811

ActiceRecord#lock! won't lock any object as you thought, it'll call reload(lock: true) which append the end of the SELECT statement or pass true for "FOR UPDATE" that mean an sql SELECT .. FOR UPDATE will be called so that a database lock (an exclusive row lock ?, depend on database) be created, return a locked record, that is what lock! imply for, not lock the object.

q = Question.first 
# SELECT "questions".* FROM "questions" ORDER BY "questions"."id" ASC LIMIT $1  ...
q.lock! 
# SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 FOR UPDATE ...

And that lock will be released after the select query done.

Upvotes: 1

Jaffa
Jaffa

Reputation: 12709

ActiveRecord::Locking::Pessimistic is made to be used with transactions, which means that lock! should be called inside a transaction and the lock will be released when the transaction commits or rolls back.

You can also use with_lock do ... end to create the transaction and lock the field automatically.

Upvotes: 4

Related Questions