💎 Ruby on Rails
Intermediate
What is ActiveRecord dirty tracking?
Answer
ActiveRecord dirty tracking detects changes to model attributes since they were last saved. Key methods: model.changed? (any unsaved changes?), model.changed (array of changed attribute names), model.changes (hash of attribute → [old, new]), model.name_changed? (was :name changed?), model.name_was (old value), model.name_change ([old, new]). Use in callbacks: before_save { update_slug if name_changed? }. After save, the previous changes are accessible via model.previous_changes. This is implemented by ActiveModel::Dirty, also available in non-ActiveRecord models.
Previous
What are Rails concerns and when should you use them?
Next
What is metaprogramming in Ruby/Rails and give examples?