This tutorial guides you through the process of using filters and callbacks in Rails. Rails filters and callbacks are powerful tools that allow you to run specific code at specific times during the controller's lifecycle.
By the end of this tutorial, you will be able to:
- Understand what filters and callbacks are in Rails.
- Use filters and callbacks in your Rails applications.
- Implement controller logic efficiently using filters and callbacks.
Basic understanding of Ruby on Rails and MVC architecture is required.
Filters are methods that are run "before", "after" or "around" a controller action. They are inherited, so if you set a filter on ApplicationController
, it will be run on every controller in your application.
class ApplicationController < ActionController::Base
before_action :authenticate
def authenticate
# authentication logic here
end
end
In the above code, :authenticate
method will be executed before every action in your application.
Callbacks are methods that get called at certain moments of an object's life cycle. For example, you might want to run a custom method before an object is saved. Callbacks make this possible.
class Post < ApplicationRecord
before_save :capitalize_title
def capitalize_title
self.title.capitalize!
end
end
In this example, the capitalize_title
method will be run before every save of a Post
object.
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
def find_post
@post = Post.find(params[:id])
end
end
In this code, find_post
method is executed before the actions 'show', 'edit', 'update' and 'destroy'. This reduces redundancy as we do not have to write the same line of code for these actions.
class User < ApplicationRecord
after_create :send_welcome_email
def send_welcome_email
UserMailer.welcome(self).deliver
end
end
In this example, send_welcome_email
is a callback that is executed after a User
object is created. This is useful for sending a welcome email to a new user after they register.
In this tutorial, we discussed filters and callbacks in Rails. We learned how to use before_action
and after_create
to run code at specific times. We also saw how these tools can help us write DRY (Don't Repeat Yourself) and clean code.
For further learning, you can explore other types of filters and callbacks in Rails, such as around_action
and before_save
.
Create a before_action
filter to authenticate a user before every action in the OrdersController
.
Create an after_save
callback in the Comment
model to send a notification email to the post author whenever a new comment is saved.
Create an around_save
callback in the Product
model to measure how long the save operation takes.
Hint: You can use Time.now
before and after the yield to get the start time and end time.
Take time to practice these concepts to get a better understanding. Happy coding!