Recently, I have found many bugs in the deadlock in my application.
Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO `products`....
code as below:
After the user has been created, I will add some products to the user. I do not understand why there was a dead end.
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 did not find the root cause, can someone give me advice? Thanks in advance.
source share