ActiveModel::Dirty Attribute Change

github logo ・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.

twitter logo DISCUSS
Classic DEV Post from Jul 17

My 2019 Remote Office Tour 🚀

Maynard Cabalitan profile image
Ruby on rails dev