[英]ActiveRecord transaction not rolling back on failure
我正在尝试使用ActiveRecord::Base.transaction
来确保一次创建Customer
, CustomerAccount
和StockNotification
,或者如果其中一个失败则完全不创建
这是我的交易
stock_notification.rb:
validates_presence_of :email
def self.make parameters
ActiveRecord::Base.transaction do
shop_id = ProductVariant.find(parameters[:product_variant_id]).shop_id
parameters[:customer_account_id] = CustomerAccount.find_or_make!(parameters[:email], shop_id).id
@stock_notification = StockNotification.create(parameters) # reference A
end
@stock_notification
end
您可能也需要这个
customer_account.rb:
def self.find_or_make! email, shop_id
customer = Customer.where(email: email).first_or_create!
CustomerAccount.where(shop_id: shop_id, customer_id: customer.id).first_or_create!
end
如果我用空白电子邮件呼叫StockNotification.make
,则create
失败(参考A),并且没有创建库存通知,但问题是仍在创建Customer
/ CustomerAccount
。
因此, transaction
根本没有完成它的工作,还是我错过了一些东西?
是的 如果引发异常,则事务将失败。 您不应使用create
,而应使用create!
在失败的情况下将这样做。 看这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.