LoginSignup
0
0

More than 5 years have passed since last update.

コールバック :バリデーション時、保存時に自動的に特定の処理を実行

Last updated at Posted at 2017-02-28

メソッドとしてオーバーライドする

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


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