title: Potential race condition in Rails 4
body: <p>Given User and Transaction models:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many     :transactions
  end
  
  class Transaction &lt; ActiveRecord::Base
    belongs_to :user
  end
  </code></pre>
  
  <p>The problem arise with an API called too frequently:</p>
  
  <pre><code>def trx
    User.transaction do
  
      user       = User.where(id: @data.user.id).lock(true).first
      trx_number = user.transactions.count + 1
  
      # some work
  
      user.transactions.create(...)
  
      change_balance = ...
  
      user.balance = user.balance.to_f + change_balance.to_f
  
      inform_user = user.has_valid_informee
  
      if !result &amp;&amp; inform_user
        inform_user.balance     = inform_user.aff_balance.to_f + @amount.to_f
        inform_user.save!
      end
  
      user.save!
    end
  
  end
  </code></pre>
  
  <p>First I've got a race condition with updating user balance using just <code>@data.user</code>, sometimes new request finish before previous thus we lost some data. Instead I started requesting lock on that user.</p>
  
  <p>Next race condition was with counting total transactions, and as I see it now we will have another RC with inform_user.</p>
  
  <p>So the question is am I doing smth wrong? Is it a good way to rewrite updating balance of inform_user with:</p>
  
  <pre><code>    inform_user.with_lock do
        inform_user.balance     = inform_user.aff_balance.to_f + @amount.to_f
      end
  </code></pre>
  
  <p>And another question, is it a good way to use nesting locks, for example when I need to update relation models while updating a parent one?</p>