LoginSignup
1
1

More than 5 years have passed since last update.

ActiveRecordのcallbackについてまとめてみた

Posted at

ActiveRecordのcallbackについてまとめてみた

1.使い方:
ActiveRecordを継承したmodel内で使う。
class Hoge < ActiveRecord::Base
before_validation :hoge
...
private
def hoge
...
end
end

みたいな感じ。

2.動作するタイミング
beofre_xx: xxする前に :hoge メソッドを実行する
after_xx: xxしたあと メソッドを実行する
arround_xx: [TBD]

xx_save: saveするとき:hoge メソッドを実行する。crate+updateのとき。
xx_create: create するとき:hoge メソッドを実行する。最初に1回だけ動く。
xx_update: update するとき:hoge メソッドを実行する。最初にレコードが作られたときは動かないが、更新時に動く。
xx_validation: validate するとき:hoge メソッドを実行する。null: false の要素に値を投入するときに使う。xx_saveより動作タイミングが早い。また、is_valid?でも動く。 saveよりも動作回数多い。

1
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
1
1