LoginSignup
0
0

More than 5 years have passed since last update.

[Rails]attributeの変更を検知

Posted at

実現したかったこと

Hogeモデルがupdateされた際に、fugaというattributeが変更されていたら特定の処理をする。

はじめはこうした

class Hoge < ActiveRecord::Base
  attr_accessor :fuga_was
  before_update :get_fuga
  after_update  :piyo

  private
  def get_fuga
    self.fuga_was = self.fuga
  end

  def piyo
    if self.fuga != self.fuga_was
      # 処理
    end
  end
end

before_updateでfugaの値をコピーしておくことで比較。
冗長ではあるけれどこれで動くだろうと思ったが…

しかし想定通り動かない

get_fugaした値はHoge.update(params)のparamsを受け取ったあとの値になっていた。(callbackの実行タイミングの問題?)

Railsに使えるメソッドが定義されている

ググってみたら、そのものズバリな質問と回答に出会う。
参考
要約すると、ActiveRecord(正確にはActiveModel::Dirty)は[attribute]_wasというメソッドを定義している。また[attribute]_changed?も定義する。

これでよかった

class Hoge < ActiveRecord::Base
  after_update :piyo

  private
  def piyo
    if self.fuga_changed?
      # 処理
    end
  end
end
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