AR삽질러

Rails 一日一つメソッド (Day51) Active Record(8) - before_update, after_update, around_update 본문

Ruby/RubyOnRails-日本語

Rails 一日一つメソッド (Day51) Active Record(8) - before_update, after_update, around_update

아랑팡팡 2024. 3. 12. 12:21
728x90

 

Rails 一日一つメソッド (Day51) Active Record(8) - before_update, after_update, around_update

 

1. before_update, after_update, around_updateとは

 - RailsでDataBase RecordがUpdateされる 「前」、「後」、または、周辺で行われるメソッド。

 

2. before_update

 - DataBase RocordがUpdateされる 「前」に行われ、Updateされる前に、Fieldを変更したり検証することができる。

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

 

 UserがUpdateされる前にEmailを小文字に変換し前と後の空白を削除して保存する。

 

class User < ApplicationRecord
	before_update :check_email_change
    
    private
    	def check_email_change
        	if email_changed?
            	puts "#{email_was}が #{email}に変更されました"
            end
        end
end

UserがUpdateされる前に、Email変更について変更履歴を残す。

 

3. ater_update

 - DataBase RecordがUpdateされた「後」に行われ、Updateされた後に、Logを残したりする。

class User < ApplicationRecord
	after_update :notify__updated_user
    
    private
    	def notiry_updated_user
        	NotificationService.send_notification("Updated User: #{nickname}")
        end
end

 

ユーザーが更新された後にユーザーに通知を送信するタスクを行う。

 

class User < ApplicationRecord
	after_update :notify_admin
    
    private
    	def notify_admin
        	AdminMailer.user_update_notification(self).deliver_now
        end
end

UserがUpdateされたら adminに通知メイルを送る。

 

4. around_update

 - DataBase RecordがUpdateされる前と後実行されるブロックがあり、「前」「後」にロジックを実行できる。

class User < ApplicationRecord
	around_update :log_update
    
    private
    	def log_update
        	puts "Before update : #{nickname}"
            yield
            puts "After update : #{nickname}"
        end
end

 

class User < ApplicationRecord
	around_update :measure_update_time
    
    private
    	def measure_update_time 
        	start_time = Time.now
            yield
            end_time = Time.now
            puts "User更新まで #{end_time - start_tiem}がかかりました"
        end
end

Update前、後の時間を測定する。

 

 

728x90
반응형
LIST