AR삽질러

Rails 一日一つメソッド (Day50) Active Record(7) - before_commit, after_commit 본문

Ruby/RubyOnRails-日本語

Rails 一日一つメソッド (Day50) Active Record(7) - before_commit, after_commit

아랑팡팡 2024. 3. 11. 11:29
728x90

 

Rails 一日一つメソッド (Day50) Active Record(7) - before_commit, after_commit

 

1. before_commit, after_commit

 - RailsのActive Recordコールバックの一つとして、トランザクションがCommitされる 「前」、「後」に実行されるメソッドで、オブジェクトの変更がDataBaseに永久的に反映される前と後に追加作業行うことになる。

 

2. before_commit

 - トランザクションがCommitされる前に行われ、Modelのオブジェクトの変更がDataBaseに永久的に反映される前に実行され、変更の確認、追加作業を行う。

 

2-1) Modelに before_commit追加

class User < ApplicationRecord
	before_commit :some_before_commit
    
    private
	    def some_before_commit
    		puts "before_commit実行"	
	    end
end
user = User.new(name: "Arang")
user.save
# some_before_commit 出力

 

2-2) Userが入力したEmailを normalizeする。

class User < ApplicationRecord
	before_commit :normalize_before_commit
    
    private
    	def normalize_before_commit
        	self.email = email.downcase.strip if email.present?
        end
end

Emailを正規化し、Emailを小文字で変更し、空白を削除してDataBaseに保存されるときに、一貫性を持って保存される。

 

user = User.new(name: "Arang", email: "ARANG@example.com")
user.save
# arang@example.com

 

3. after_commit

 - トランザクションが完了し、DataBaseにCommitされた後に、実行されるメソッドで、after_commitで、Dataが保存された後の作業を行うことができる。

 

class User < ApplicationRecord
	after_commit :send_welcome_email, on: :create
    
    private
    	def send_welcome_email
        	UserMailer.welcome_email(self).deliver_later
        end
end

Userが生成された後、after_commitのsend_welcome_emailメソッドが実行されUserにMailを送る。.deliver_later : deliver_nowとは違う、非同期的に送信する方法で、バックグラウンドで処理され、ウェブ リクエストをブロックせずにユーザーにすぐ送信する。

 

728x90
반응형
LIST