AR삽질러

Rails 一日一つメソッド (Day48) Active Record(5) - before_save, after_save, around_save 본문

Ruby/RubyOnRails-日本語

Rails 一日一つメソッド (Day48) Active Record(5) - before_save, after_save, around_save

아랑팡팡 2024. 3. 7. 14:34
728x90

 

Rails 一日一つメソッド (Day48) Active Record(5) - before_save, after_save, around_save

 

1. before_save, after_save, around_save

 - RailsのActiveRecordでは、DataBase Recordの保存前(before_save)、保存後(after_save)、保存周辺(around_save)でコールバックを設定できる。

 

before_save

 - Recordが保存される前に、実行され、DataBaseにRecordを保存する前にFieldを更新したり検証する時に使う。

 

after_save

 - Recordが保存された後に実行され、RecordがDataBaseに保存された後に、追加作業を行う時に使う。

 

around_save

 - Recordが保存される前(before_save)、保存された後(after_save)に実行され、ロジックを実行できる。

 


2. before_save

 2-1) UserをUpdateする時にEmailを小文字に変更したい時

class User < ApplicationRecord
	before_save :downcase_email
    
    private
    	def downcase_email
        	sefl.email = email.downcase
        end
end

 

 - UserがEmailを入力し、Emailを保存する前に、小文字で変換し、DataBaseに保存する。

 

 2-2) Userのユーザーの名前と姓を組み合わせてニックネームを作成する。

class User < ApplicationRecord
	before_save :generate_nickname
    
    private
    	def generate_nickname
        	self.nickname = "#{first_name}_#{last_name}"
        end
end

 

 2-3) User写真Upload時、resizeする。

class User < ApplicationRecord
	before_save :resize_image
    
    private
    	def resize_image
        	if profile_image.attached? && profile_image.blob.variable?
            	resized_image = profile_image.variant(resize: '300x300').processed
                profile_image.attach(resized_image)
            end
        end
end

 

profile_image.attached?

 - profile_imageを登録したのかを確認する。

profile_image.blob.variable?

 - blob.variableで、写真が変換できるのかを確認する。

profile_image.variant(resize: '300x300').processed

 - 写真をresizeし、.processedで、変換を実装する。

 

 

3. after_save

 3-1) Userが保存される時、logを出力する。

class User < ApplicationRecord
	after_save :log_user_saved
    
    private 
    	def log_user_saved
        	puts "Userが #{id}保存されました"
        end
end

 

User保存に成功したら、指定したメッセージが出力される。

 

 3-2) User登録に成功した時、歓迎のMailをUserに送る。

class User < ApplicationRecord
	after_save :send_welcome_email
    
    private
    	def send_welcome_email
        	UserMailer.with(user: self).welcome_email.deliver_now
        end
end

 

4. around_save

 4-1) around_saveが呼び出される時を確認する。

class User < ApplicationRecord
	around_save :log_save_process
    
    private
    	def log_save_process
        	puts "User保存"
            yield
            puts "User保存成功"
        end
end

 

log_save_processで、Userを保存する前にメッセージを出力し、yieldで保存を行う、その後、保存ができたら成功メッセージが出力される。

728x90
반응형
LIST