When lock Is release on object in rails?

Viewed 696

I have one function in model class and inside that function I am doing like this,

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

So on above case when will lock release from object?

And here Note : I am not writing this inside the transactions block.

2 Answers

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.

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.

Related