Using Before and After Filters in Rails Controllers
📖 Scenario: You are building a simple Rails web app to manage a list of books. You want to run some code automatically before and after certain actions in your controller to prepare data and log activity.
🎯 Goal: Create a Rails controller called BooksController that uses before_action and after_action filters. The before_action will set a variable with a welcome message before the index action. The after_action will log a message after the index action runs.
📋 What You'll Learn
Create a
BooksController class inheriting from ApplicationControllerAdd a
before_action filter named set_welcome_message that runs only before the index actionAdd an
after_action filter named log_index_access that runs only after the index actionDefine the
index action that sets an instance variable @books to an array of book titlesDefine the
set_welcome_message method that sets @welcome_message to the string "Welcome to the Books List!"Define the
log_index_access method that calls Rails.logger.info with the message "Index action was accessed"💡 Why This Matters
🌍 Real World
Before and after filters are used in Rails apps to run code automatically around controller actions. For example, setting up data, checking permissions, or logging activity without repeating code in every action.
💼 Career
Understanding filters is important for Rails developers to write clean, maintainable controllers and implement common behaviors like authentication, logging, and data preparation efficiently.
Progress0 / 4 steps