How to Use Callbacks
Explore how to effectively use Active Record callbacks in Rails models to normalize data and track database activity. Understand when callbacks are beneficial, such as for managing cross-cutting concerns and ensuring consistent data representations. Learn best practices to avoid common pitfalls by applying callbacks strategically within the model lifecycle, enhancing code clarity and app reliability.
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 ...