title: Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO
body: <p>Recently, I found lots of deadlock errors in my application.</p>
  
  <pre><code>Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO `products`....
  </code></pre>
  
  <p>the code as below:</p>
  
  <p>After user has been created, I will add some products to user. I don't understand why deadlock happened.</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
      after_create :add_products
      has_many :products, :dependent =&gt; :destroy
  
      def self.create_user
        User.create!(.......)
      end
  
      def add_products
        Product.add(self, "product_name", 10)
      end
      .....
  end
  
  class Product &lt; ActiveRecord::Base
      belongs_to :user
  
      def self.add(user, product_name, amount)
         transaction do
           product = user.products.find_by_product_name(product_name)
           if product
              product.increment :amount, amount
              product.save!
           else
              product = self.create! user_id: user.id,
                                     product_name: product_name,
                                     amount: amount
           end
         end
         product
      end
  end
  </code></pre>
  
  <p>I didn't find the root cause, can anyone give me some advice? Thanks in advance!!!</p>