2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】コールバックとは

Last updated at Posted at 2022-02-21

コールバックとは

モデルを保存、更新、削除後や削除前のタイミングで実行されるメソッドのこと指す。
例) 記事を投稿し保存後には〜をする。

before_save => #保存前
after_save => #保存後
after_update => #更新後
before_destroy => #削除前
after_destroy => #削除後

使用例

例①
before_save(保存前)コールバック後にメソッド実行。
下記コードはemail保存前に、大文字のローマ字がある場合、小文字に変換するメソッド。

class << self
  before_save :downcase_email
  def downcase_email
     self.email = email.downcase
  end

例②

class ShopsController < ApplicationController
  before_action :logged_in_user

上記はpostsコントローラーの各アクション前にログインユーザーであることを指定している。

ネットで何か購入する時、ログインしていない場合はログインまたは会員登録を促されると思われるが、ログインユーザーでないため、弾かれる(before_action :logged_in_user)のもコールバックによりログインを要求しているものと言える。

使用できるコールバック一覧(呼び出される順)

オブジェクトの作成

before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit / after_rollback

オブジェクトの更新

before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit / after_rollback

オブジェクトに削除

before_destroy
around_destroy
after_destroy
after_commit / after_rollback

参考記事

Active Record コールバック
【Rails】コールバックについて

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?