簡體   English   中英

如果ActiveRecord :: Base.transaction成功,請執行一些操作

[英]If ActiveRecord::Base.transaction succeeded, do something

如何檢查ActiveRecord :: Base.transaction是否成功?

我希望在出現問題時進行回滾,但是我也想確保如果交易成功,我會做一些額外的邏輯。 這是代碼:

#...
ActiveRecord::Base.transaction do
  user_id = existing_ids.last || User.create(phone: phone_number)
  homes.update_all(user_id: user_id)
end

if transaction_was_success
  # do something
else 
  # do something else
end

要在成功交易后執行額外的工作,可以使用after_commit回調。

要在事務期間發生故障時觸發回滾,請使用! 方法。 使用update_all方法的問題是它不會引發任何錯誤。 update_attribute! 是一個! 方法,因此會在失敗時引發錯誤。 現在,如果任何更新或創建失敗,它將回滾事務。

after_commit :successful_commit

ActiveRecord::Base.transaction do
  user_id = existing_ids.last || User.create!(phone: phone_number)
  homes.each do |home|
     home.update_attribute!(user_id: user_id)
  end

  # Or do other things here...
end

def successful_commit
   # Something on success here...
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM