最近,我在我的应用程序中发现了许多死锁错误。
Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO `products`....
以下是代码:
用户被创建后,我会向用户添加一些产品。我不理解为什么会发生死锁。
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
我没有找到根本原因,有人能给我一些建议吗?先谢谢了!!!