What if you could write login checks and logs just once and have Rails do the rest automatically?
Why Before and after filters in Ruby on Rails? - Purpose & Use Cases
Imagine you have a web app where you must check user login before every page loads and log every action after it finishes.
You write this check and log code inside every controller action manually.
Manually adding the same code everywhere is tiring and easy to forget.
If you miss one place, your app might let unauthorized users in or skip important logs.
It also makes your code messy and hard to update later.
Before and after filters let you run code automatically before or after controller actions.
You write the check or log once, and Rails runs it for all relevant actions.
This keeps your code clean, consistent, and easy to maintain.
def show check_login # show action code log_action end
before_action :check_login after_action :log_action def show # show action code end
You can easily add shared behavior across many actions without repeating code, making your app safer and cleaner.
In a blog app, you want to verify the user is logged in before editing posts and log every edit after it happens.
Using filters, you add these checks once and they run automatically for all edit actions.
Manual repetition of checks and logs is error-prone and messy.
Before and after filters run code automatically around actions.
This keeps your app secure, clean, and easier to maintain.
Practice
before_action filter in a Rails controller?Solution
Step 1: Understand the role of filters
Filters in Rails run code around controller actions to modify behavior.Step 2: Identify the timing of
before_actionbefore_actionruns code before the main action method executes.Final Answer:
To run code before a controller action executes -> Option AQuick Check:
before_action = runs before action [OK]
- Confusing before_action with after_action
- Thinking before_action skips actions
- Assuming before_action defines new actions
log_action in a Rails controller?Solution
Step 1: Recall the modern syntax for after filters
Rails usesafter_actionto define code that runs after controller actions.Step 2: Check each option
after_filter :log_action uses deprecatedafter_filter. after_action :log_action uses correctafter_action. before_action :log_action is for before filters. after :log_action is invalid syntax.Final Answer:
after_action :log_action -> Option DQuick Check:
Use after_action for after filters [OK]
- Using deprecated after_filter instead of after_action
- Mixing before_action with after filters
- Incorrect syntax like 'after :method'
class PostsController < ApplicationController
before_action :set_post
after_action :log_post
def show
render plain: @post.title
end
private
def set_post
@post = Post.find(params[:id])
end
def log_post
Rails.logger.info "Post viewed: #{@post.id}"
end
endWhat will be the output when
GET /posts/5 is called, assuming the post with ID 5 has title "Hello"?Solution
Step 1: Understand filter order and effects
before_action :set_postruns beforeshow, setting @post.after_action :log_postruns aftershowcompletes.Step 2: Trace the request flow
Whenshowruns, @post is set, sorender plain: @post.titleoutputs "Hello". After rendering,log_postlogs "Post viewed: 5".Final Answer:
The page shows "Hello" and logs "Post viewed: 5" after rendering -> Option AQuick Check:
before_action sets data, after_action logs after render [OK]
- Thinking after_action runs before rendering
- Assuming @post is nil in show
- Confusing logging output with page content
class UsersController < ApplicationController
before_action :authenticate_user
after_action :clear_session
def index
# list users
end
private
def authenticate_user
redirect_to login_path unless current_user
end
def clear_session
session[:temp] = nil
end
endSolution
Step 1: Analyze filter behavior with redirects
Ifauthenticate_userredirects, the action does not run, butafter_actionstill runs.Step 2: Understand consequences of after_action after redirect
Runningclear_sessionafter redirect can cause unexpected side effects or errors.Final Answer:
The after_action runs even if redirect happens, causing errors -> Option CQuick Check:
after_action runs even after redirect [OK]
- Assuming after_action skips on redirect
- Thinking authentication should be after_action
- Believing private methods must be public
before_action filter named check_admin only before the edit and update actions in a Rails controller. Which is the correct way to write this?Solution
Step 1: Identify correct filter type and options
Usebefore_actionto run code before actions. Useonly:to limit to specific actions.Step 2: Evaluate each option
before_action :check_admin, only: [:edit, :update] correctly usesbefore_actionwithonly: [:edit, :update]. before_action :check_admin, except: [:edit, :update] usesexcept, which excludes those actions. after_action :check_admin, only: [:edit, :update] usesafter_action, wrong timing. before_filter :check_admin, only: [:edit, :update] uses deprecatedbefore_filter.Final Answer:
before_action :check_admin, only: [:edit, :update] -> Option BQuick Check:
Use before_action with only: for specific actions [OK]
- Using except instead of only
- Using after_action instead of before_action
- Using deprecated before_filter
Ready to prove it?
Pass the test and this pattern moves unknown
