How to Use Callbacks
Learn about implementing and leveraging callbacks in our Rails application for enhanced functionality.
We'll cover the following
Active Record has a detailed set of callbacks available that allow us to run code at various points of a model’s life cycle. The use of these callbacks is hotly debated, and their proper intended use is unclear. Some developers tend to model all business processes as the life cycle of an Active Record and use callbacks to implement the business logic.
The way we suggested implementing business logic is totally different; thus, we don’t end up having many problems that callbacks could solve.
That said, there are occasions where they can be useful. Let’s talk about two that we’ve found to be common. The first is as a place for data normalization logic. The second is for managing cross-cutting operational concerns related to database access.
Normalizing data in before_validation
Our database stores data using rudimentary data types. While we can use constraints to ensure the data is correct and validations to help users get it right, we also often want to translate values that mean the same thing into one canonical value. For example, any string that contains only whitespace might be best stored as nil
.
We can certainly do this in the attribute method setters, but Active Records have several different ways of setting the value, and it can be unclear whether we’ve got the right one. It can often be easier to use the before_validation
callback to do this normalization. For example, if we want all empty strings for a widget’s name to be normalized to nil
, we could do this:
Get hands-on with 1200+ tech skills courses.