Skip to content

Latest commit

 

History

History
50 lines (39 loc) · 1.97 KB

when_to_use_after_commit_with_active_record.md

File metadata and controls

50 lines (39 loc) · 1.97 KB
title date draft categories tags author showToc TocOpen hidemeta comments description canonicalURL disableShare disableHLJS hideSummary searchHidden ShowReadingTime ShowBreadCrumbs ShowPostNavLinks ShowWordCount ShowRssButtonInSectionTermList UseHugoToc editPost
when_to_use_after_commit_with_active_record
2022-10-09 23:03:57 +0800
false
Rails
Active Record Callback
Active Record
Me
true
false
false
true
[Rails] after_commit, 何時會用到它
false
false
false
true
true
true
true
true
true
true
URL Text appendFilePath
Suggest Changes
true

after_commit 是一種 Actice RecordCallback

當我們透過 Active Record 與資料庫互動時,有許多的時機點可以觸發 Active Record Callback,對資料做檢查或是儲存後的其他操作.

使用情境

舉一個之前專案的例子,在網站上有許多的組織以及其中的成員,當我們新增成員加入組織時,我們需要寄信通知組織的管理員(有成員加入組織等等...)

我們可以在 model.rb 中利用 after_save 去執行寄信,當成員成功加入組織後(user.save),執行寄信程式,儘管看起來沒問題,寄信程式的確會在 user.save 成功後執行。

但從資料庫的角度來看,如果新增成員後還有其他操作,一旦失敗,資料庫便會將整個 transaction 退回,即 ACID 中的 Atomicity (全部成功、或全部失敗)

而這時背景執行的寄信程式,便無法正確執行

因此,我們可以改用 after_commit callback ,確保資料庫 transation 成功 commit 後,才呼叫寄信程式寄信。

reference

https://blog1.westagilelabs.com/when-to-use-after-commit-in-rails-f5e53a22bb9

https://guides.rubyonrails.org/v6.1/active_record_callbacks.html