Exploratory Guide on Active Model Dirty in Rails

2023/07/21
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

Rails, the superhero of web frameworks, comes packed with amazing features that make our development journey easier. Among its arsenal of superpowers, we have "ActiveModel::Dirty" — a nifty tool that helps us determine if our object attributes have undergone any changes and empowers us to take the appropriate actions accordingly.

ActiveModel::Dirty allows us to keep track of attribute modifications in our ActiveRecord objects. When we modify an attribute, Rails secretly keeps track of the original value before making the change. This way, we can compare the "before" and "after" values and perform actions based on the changes.

To unlock the power of ActiveModel::Dirty, we simply need to add include ActiveModel::Dirty to our object. This activates the superpowers and allows us to use the Dirty methods.

For example, let's bring in a model named "Bunny" to the scene. Initially, if we ask our bunny if it has undergone any changes with bunny.changed?, it might look at us innocently and say, "Nah, no changes here!" But fear not, for our bunny is ready for action! Now, let's assign a value to one of its attributes, such as the "name" attribute. If we call the Dirty methods, we can see that our bunny proudly proclaims, "I've been changed!"

But what if we want to take a peek at the changes even after saving? Our bunny has a secret stash of information! With bunny.previous_changes, it spills the beans and reveals the history of modifications. We can examine all the attributes that underwent changes, including timestamps like "created_at" and "updated_at".

In case we want to start afresh, our bunny can hit the "reload" button and wipe the slate clean. It can also use its restore_attributes superpower to revert back to the original values.

ActiveModel::Dirty tracking in Rails is like having a vigilant sidekick keeping an eye on our attribute modifications. It provides us with the tools to easily track and respond to changes in our objects, making our development process smoother and more efficient.