0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsのafter_saveとafter_createの違い

Posted at

Railsのafter_saveafter_createの違い

主な違いは以下です!

  1. 実行タイミング:

    • after_save: レコードが保存されるたびに実行されます(新規作成時も更新時も)
    • after_create: レコードが新規作成された時のみ実行されます
  2. 使用シーン:

    • after_save:

      • レコードの作成・更新の両方で実行したい処理がある場合
      • 例:ログの記録、キャッシュの更新、関連レコードの更新など
    • after_create:

      • 新規作成時のみ実行したい処理がある場合
      • 例:ウェルカムメールの送信、初期データの設定、一意の識別子の生成など
  3. コード例:

class User < ApplicationRecord
  # 新規作成時のみ実行
  after_create :send_welcome_email
  
  # 保存時(作成・更新)に実行
  after_save :update_cache
  
  private
  
  def send_welcome_email
    UserMailer.welcome_email(self).deliver_later
  end
  
  def update_cache
    Rails.cache.write("user_#{id}", self)
  end
end
  1. パフォーマンスの考慮:

    • after_saveは更新時にも実行されるため、更新頻度が高いモデルでは注意が必要
    • 更新時には不要な処理をafter_createに移動することで、パフォーマンスを改善できる可能性があ
  2. 注意点:

    • コールバック内で同じモデルを更新すると、無限ループが発生する可能性がある
    • コールバック内での処理は、できるだけ軽量に保つこと
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?