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