Callbacks are methods that we can call in an object’s life cycle at certain moments, like after a change of state. While using callbacks, it is possible to write codes whenever an active record object is created, saved, updated, deleted, loaded, or validated from the database.
Callbacks allow greater control of both the data and the applications using the data.
Callbacks alter the usual linear flow of the code, making the debugging and test-making process more difficult.
We have three choices for callbacks. Not all objects support callbacks, but the following are the three basic options:
before_create
– Runs before the stated object.
after_create
– Runs after the stated object.
around_create
– We will write a method that actually yields at some point to the original action. This way, you can have code both before and after the original action, and you decide at which point the original action gets done.
To use a callback, you need to “register” it at the top of your Model using the appropriate method (e.g., before_create). You either pass that method a symbol that corresponds to the method name or write the callback as a block then and there. Rails will hang onto that method and call it at the appropriate time. For example:
class User < ActiveRecord::Basebefore_create do |user|puts "Creating #{user.name}"endafter_create :Createdprivatedef just_createdputs "User Created."endend
In this example, we make a class that is linked with the database. We call the before_create
to check some requirements. After that, we call the after_create
, which shows the message.
Free Resources