そういうことだったんですね

いろいろ調べたり学んだりしたことを忘れないように書き連ねています

rails - ActiveRecord の コールバック

基本

  • オブジェクトの生成・更新・削除のタイミングで呼び出されるメソッド
  • トリガとなるイベント(validation,saveなど)の前(before)と後(after)に登録可能
  • コールバックはメソッドチェーンに追加される。
  • before_xxx で false を返すか例外を発生させると、それ以降の処理を停止させることができる (トランザクション中の場合は ROLLBACK を発生させる)

使い方

  • before_xxxx/after_xxxx メソッドでコールバックとするメソッド名を登録
  • メソッドを定義する

class Blog < ActiveRecord::Base
  after_save :saved_title

  protected
  after_validation :saved_title
    puts "Saved!!"
  end
end

利用可能なコールバックの種類と実行順序

Create
  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create
  • around_create
  • after_create
  • after_save
Update
  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_update
  • around_update
  • after_update
  • after_save
Destroy
  • before_destroy
  • around_destroy
  • after_destroy
Find
  • after_initialize
  • after_find

条件付きのコールバック

:if/:unless を使うことで特定の条件のときのみコールバックを
実行させる/させないことができる

class SomeModel < ActiveRecord::Base
  before_save :some_action, if: :action_condition?

  protected
  def action_condition?
  end
end

:if/:unless には、シンボル、文字列、手続きオブジェクトが指定できる

モデルから再利用する

クラスにコールバック名と同名のメソッドを定義し、コールバックメソッド
にオブジェクトを渡す。

class SomeCallback
  def before_save
    # ...
  end
end

class SomeModel < ActiveRecord::Base
  before_save SomeCallback.new
end