title: How to fix and test a race-condition in my Rails 4 model
body: <p>I had the following code in my model. Someone rightly pointed out that the <code>make_default!</code> method could cause a race condition:</p>
  
  <pre><code>class State &lt; ActiveRecord::Base
    def make_default!
      State.update_all(default: false)
      update!(default: true)
    end
  end
  </code></pre>
  
  <p>because if two people are updating the record at the same time, two <code>State</code> objects could end up being set to <code>default: true</code>.</p>
  
  <p>I used this workaround by using ActiveRecord locks:</p>
  
  <pre><code>class State &lt; ActiveRecord::Base
    def make_default!
      # Prevent race condition using database-level locks.
      State.transaction do
        State.where.not(id: id).lock(true).update_all(default: false)
        State.where(id: id).lock(true).first.update!(default: true)
      end
    end
  end
  </code></pre>
  
  <p>but someone pointed out that this could cause other potential bugs.
  I'm wondering what the best way to implement locks would be, as well as how I'd go about testing the model spec (using RSpec)?</p>
  
  <p>Any help much appreciated :) thanks!</p>