メソッドとしてオーバーライドする
app/models/user.rb
class User < ActiveRecord::Base
#メソッドとしてbefore_createコールバックを指定する
def before_create
self.encrypted_password = encrypt(self.password)
end
private
def encrypt(password)
...
end
end
シンボルで指定する
app/models/user.rb
class User < ActiveRecord::Base
before_create :encrypt_password
private
def encrypt_passwordself.encrypted_password = encrypt(self.password)
end
def encrypt(password)
...
end
end
文字列で指定する
app/models/user.rb
class User < ActiveRecord::Base
before_create "self.encrypted_password = encrpt(self.password)"
private
def encrypt(password)
...
end
end
ブロックで指定する
app/models/user.rb
class User < ActiveRecord::Base
before_create do |record|
record.encrypted_password = encrypt(record.password)
end
private
def encrypt(password)
...
end
end
コールバック用オブジェクトで指定する
app/models/user.rb
class User < ActiveRecord::Base
#before_createコールバックとして、コールバック用オブジェクトである
#PasswordEncryptorのインスタンスを指定する
before_create PasswordEncryptor.new("password")
end
class PasswordEncryptordef initialize(attr)
@attr_for_callback = attr
end
#before_createコールバック時に呼び出される
#引数には対象となっているモデルオブジェクトが渡される
def before_create(record)
record.encrypted_password =
encrypt(record.send(@attr_for_callback))
end
private
df encrypt(password)
...
end
end
バリデーション時、保存時に自動的に特定の処理を実行 コールバック
モデルオブジェクト create コールバック
save
valid?
before_validation
validate
after_validation
before_save
before_create
create
after_create
after_save
モデルオブジェクト update コールバック
save
valid?
before_validation
validate
after_validation
before_save
before_update
update
after_update
after_save