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
<span style="font-weight: 400;"> def update_color</span>
<span style="font-weight: 400;"> if color_was == Color.BLUE </span>
<span style="font-weight: 400;"> write_attribute(:color, color) </span>
<span style="font-weight: 400;"> end</span>
<span style="font-weight: 400;"> end</span>
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.