loading...

ActiveModel::Dirty Attribute Change

webcoderph profile image Maynard Cabalitan ・1 min read

Sometimes we need to check specific attribute if change from it previous value before running an api for request limit.

The solution is activemodel::dirty

for after save

saved_change_to_attribute?

for before save

will_save_change_to_attribute?

Example

class User
  after_save api_update, if: :saved_change_to_name?
  before_save api_update, if: :will_save_change_to_position?

  def api_update
  end
end

These callbacks will run only if the attributes change from its previous value.

Discussion

pic
Editor guide