title: Database lock not working as expected with Rails & Postgres
body: <p>I have the following code in a rails model:</p>
  
  <pre><code>foo = Food.find(...)
  foo.with_lock do
    if bar = foo.bars.find_by_stuff(stuff)
      # do something with bar
    else
      bar = foo.bars.create!
      # do something with bar
    end
  end
  </code></pre>
  
  <p>The goal is to make sure that a Bar of the type being created is not being created twice.</p>
  
  <p>Testing with_lock works at the console confirms my expectations. However, in production, it seems that in either some or all cases the lock is not working as expected, and the redundant Bar is being attempted -- so, the with_lock doesn't (always?) result in the code waiting for its turn.</p>
  
  <p>What could be happening here?</p>
  
  <p><strong>update</strong>
  so sorry to everyone who was saying "locking foo won't help you"!! my example initially didin't have the bar lookup. this is fixed now.</p>