From the course: Ruby on Rails Models and Associations

Unlock the full course today

Join today to access over 24,200 courses taught by industry experts.

Use callbacks to automate actions

Use callbacks to automate actions

- [Instructor] Now that we understand how callbacks work, in this movie we'll learn to write them in our code. This example shows a customer model with three callbacks. The first is a before validation callback to format a phone number. Phone numbers may be submitted in a variety of formats containing dashes, spaces, periods, and more. I imagine this callback is a method to standardize the format so that it can be more easily validated. The second callback is a before save callback to geocode the address. It might contact a third party service to get back a latitude and longitude to store the database at the same time as the record saves. The third is an after commit callback called notify admins. Anytime a record is created, updated, or destroyed, it will send a message to admins. Notice that it uses after commit and not after save. So it only takes place once the transaction is final. Each callback has the name of a private…

Contents