Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locking rows on rails update to avoid collisions. (Postgres back end)

So I have a method on my model object which creates a unique sequence number when a binary field in the row is updated from null to true. Its implemented like this:

class AnswerHeader < ApplicationRecord
  before_save :update_survey_complete_sequence, if: :survey_complete_changed?

  def update_survey_complete_sequence
    maxval =AnswerHeader.maximum('survey_complete_sequence')
    self.survey_complete_sequence=maxval+1
  end
end

My question is what do I need to lock so two rows being updated at the same time don't end up with two rows having the same survey_complete_sequence?

If it is possible to lock a single row rather than whole table that would be good because this is a often accessed table by users.

like image 205
GGizmos Avatar asked Sep 29 '17 17:09

GGizmos


1 Answers

If you want to handle this in application logic itself, instead of letting database handle this. You make make use of rails with_lock function that will create a transaction and acquire a row level db lock on the selected rows(in your case a single row).

like image 121
Gaurav Sachan Avatar answered Oct 08 '22 08:10

Gaurav Sachan