LoginSignup
7
8

More than 5 years have passed since last update.

Rails コールバックについて その1

Posted at

曖昧な理解だったコールバックについてまとめた。

コールバックとは?

オブジェクトのライフサイクル期間の特定のタイミングで呼び出されるメソッド

実際に使ってみた

決まったタイミングで必ず呼びたいメソッドは、コールバックを使用すると良さそう

下記は、postインスタンスが作られる時に、必ずurl_tokenカラムにランダムな文字列を入れる実装
before_create を使用しているので、createアクションが呼ばれる前に必ず呼ばれる

post.rb
class Post < ApplicationRecord
  belongs_to :user
  # create時に必ず呼ばれる処理
  before_create :set_rand_id

  private
   # postsテーブルのurl_tokenカラムにランダムな16桁の数字(文字列)を入れる処理
  def set_rand_id
    self.url_token = 16.times.map{rand(0..9)}.join()
  end
end

コールバックの種類

objectの作成/更新
- before_validation
- after_validation
- before_save
- around_save
- before_create(update)
- around_create(update)
- after_create(update)
- after_save

after_save は作成と更新の両方で呼び出されるが、コールバックマクロの呼び出し順にかかわらず、必ず、より具体的な after_create および after_updateよりも後に呼び出される。

objectの削除
- before_destroy
- around_destroy
- after_destroy

after_initialize と after_find

after_initialize => Active Record オブジェクトが1つインスタンス化されるたびに呼び出される
※インスタンス化は new 以外にもDBからレコードを読み込んだ時も実行される

after_find => Active Record がデータベースからレコードを1つ呼び込むたびに呼び出される

どちらも定義されている場合は、 after_find が先に呼ばれる

post.rb
class Post < ApplicationRecord
  belongs_to :user
  after_initialize do |post|
    puts "オブジェクトは初期化されました"
  end

  after_find do |user|
    puts "オブジェクトが見つかりました"
  end

>> Post.new
"オブジェクトは初期化されました"
=> #<User id: nil>

>> User.first
オブジェクトが見つかりました
オブジェクトは初期化されました
=> #<User id: 1>

続きはその2で

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