Get previous values of model attributes in Rails using a pre-existing helper
Img source: binarywebpark.com
One of the best practices is keeping your controllers with as little code as possible, and have all the validations in the models. Rails includes a lot of validations that you can use in your models, and many other helpers that help you focus on your business logic and develop your projects as quickly as possible. A helper method that is among the unpopular ones is the possibility to check the old value of an attribute of a object, before doing any database transaction.
This method is ATTRIBUTE_was, where ATTRIBUTE represents a model’s attribute.
Let’s take an example to understand it a little better.
Suppose that you have an attribute called color and you are trying to update this attribute only in cases when it was previously a blue color. In this case, we can have the following:
before_update :update_color
def update_color
if color_was == Color.BLUE
write_attribute(:color, color)
end
end
The callback added will make sure this method is called each time an object of this model is being updated.
This is just a small thing, but that is surprisingly not that much known and can be something useful that you can use in your models.