Recently, I found lots of deadlock errors in my application.
Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO `products`....
the code as below:
After user has been created, I will add some products to user. I don't understand why deadlock happened.
class User < ActiveRecord::Base
after_create :add_products
has_many :products, :dependent => :destroy
def self.create_user
User.create!(.......)
end
def add_products
Product.add(self, "product_name", 10)
end
.....
end
class Product < 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
I didn't find the root cause, can anyone give me some advice? Thanks in advance!!!