Bird
Raised Fist0
Ruby on Railsframework~20 mins

Before and after filters in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rails Filters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Rails controller with before_action?

Consider this Rails controller snippet. What will be printed when the show action is called?

Ruby on Rails
class ArticlesController < ApplicationController
  before_action :set_article, only: [:show]

  def show
    render plain: @article.title
  end

  private

  def set_article
    @article = OpenStruct.new(title: "Hello World")
  end
end
Anil
BRaises NoMethodError
C"" (empty string)
D"Hello World"
Attempts:
2 left
💡 Hint

Remember that before_action runs the method before the action method.

❓ lifecycle
intermediate
2:00remaining
Which callback runs after the action method in Rails controllers?

Given these Rails controller callbacks, which one runs after the action method?

Ruby on Rails
class UsersController < ApplicationController
  before_action :authenticate_user
  after_action :log_action

  def index
    render plain: "User list"
  end

  private

  def authenticate_user
    # authentication logic
  end

  def log_action
    # logging logic
  end
end
Abefore_action :authenticate_user
Baround_action :wrap_action
Cafter_action :log_action
Dskip_before_action :authenticate_user
Attempts:
2 left
💡 Hint

Think about which callback runs after the controller action finishes.

📝 Syntax
advanced
2:00remaining
What error does this Rails filter code raise?

Examine this Rails controller code. What error will it raise when loaded?

Ruby on Rails
class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit]

  def show
    render plain: @product.name
  end

  private

  def set_product
    @product = Product.find(params[:id])
  end
end
ANo error, code runs fine
BNoMethodError: undefined method `find' for nil:NilClass
CArgumentError: wrong number of arguments (given 0, expected 1)
DNameError: undefined local variable or method `params' for ProductsController
Attempts:
2 left
💡 Hint

Consider how params is available in controller methods.

🔧 Debug
advanced
2:00remaining
Does this after_action run when the action redirects?

In this Rails controller, will the after_action callback run?

Ruby on Rails
class OrdersController < ApplicationController
  after_action :clear_cart, only: [:create]

  def create
    # order creation logic
    redirect_to order_path(1)
  end

  private

  def clear_cart
    session[:cart] = nil
  end
end
AYes, the after_action runs even if the action redirects
BNo, the method clear_cart is private and cannot be called as a callback
CNo, the after_action is set for :create but the action name is misspelled
DNo, after_action callbacks do not run if the action redirects
Attempts:
2 left
💡 Hint

Redirects do not prevent after_action callbacks from running.

🧠 Conceptual
expert
3:00remaining
What is the order of execution for these Rails controller callbacks?

Given these callbacks in a Rails controller, what is the correct order they run when an action is called?

Ruby on Rails
class CommentsController < ApplicationController
  before_action :authenticate_user
  around_action :wrap_in_transaction
  after_action :log_comment

  def create
    # create comment logic
    render plain: "Created"
  end

  private

  def authenticate_user
    # authentication
  end

  def wrap_in_transaction
    ActiveRecord::Base.transaction do
      yield
    end
  end

  def log_comment
    # logging
  end
end
A2,1,3,5,4
B1,2,3,4,5
C1,3,2,4,5
D2,3,1,4,5
Attempts:
2 left
💡 Hint

Remember that around_action wraps the action and other callbacks.

Practice

(1/5)
1. What is the main purpose of a before_action filter in a Rails controller?
easy
A. To run code before a controller action executes
B. To run code after a controller action executes
C. To skip a controller action entirely
D. To define a new controller action

Solution

  1. Step 1: Understand the role of filters

    Filters in Rails run code around controller actions to modify behavior.
  2. Step 2: Identify the timing of before_action

    before_action runs code before the main action method executes.
  3. Final Answer:

    To run code before a controller action executes -> Option A
  4. Quick Check:

    before_action = runs before action [OK]
Hint: Before filters run code before actions start [OK]
Common Mistakes:
  • Confusing before_action with after_action
  • Thinking before_action skips actions
  • Assuming before_action defines new actions
2. Which of the following is the correct syntax to define an after filter named log_action in a Rails controller?
easy
A. after_filter :log_action
B. after :log_action
C. before_action :log_action
D. after_action :log_action

Solution

  1. Step 1: Recall the modern syntax for after filters

    Rails uses after_action to define code that runs after controller actions.
  2. Step 2: Check each option

    after_filter :log_action uses deprecated after_filter. after_action :log_action uses correct after_action. before_action :log_action is for before filters. after :log_action is invalid syntax.
  3. Final Answer:

    after_action :log_action -> Option D
  4. Quick Check:

    Use after_action for after filters [OK]
Hint: Use after_action, not after_filter, for after filters [OK]
Common Mistakes:
  • Using deprecated after_filter instead of after_action
  • Mixing before_action with after filters
  • Incorrect syntax like 'after :method'
3. Given this controller code:
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
end

What will be the output when GET /posts/5 is called, assuming the post with ID 5 has title "Hello"?
medium
A. The page shows "Hello" and logs "Post viewed: 5" after rendering
B. The page shows "Hello" but does not log anything
C. The page shows nothing and logs "Post viewed: 5"
D. An error occurs because @post is not set

Solution

  1. Step 1: Understand filter order and effects

    before_action :set_post runs before show, setting @post. after_action :log_post runs after show completes.
  2. Step 2: Trace the request flow

    When show runs, @post is set, so render plain: @post.title outputs "Hello". After rendering, log_post logs "Post viewed: 5".
  3. Final Answer:

    The page shows "Hello" and logs "Post viewed: 5" after rendering -> Option A
  4. Quick Check:

    before_action sets data, after_action logs after render [OK]
Hint: before_action sets data, after_action runs after response [OK]
Common Mistakes:
  • Thinking after_action runs before rendering
  • Assuming @post is nil in show
  • Confusing logging output with page content
4. Identify the error in this controller code:
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
end
medium
A. The methods authenticate_user and clear_session must be public
B. The before_action should be after_action for authentication
C. The after_action runs even if redirect happens, causing errors
D. There is no error; the code works as expected

Solution

  1. Step 1: Analyze filter behavior with redirects

    If authenticate_user redirects, the action does not run, but after_action still runs.
  2. Step 2: Understand consequences of after_action after redirect

    Running clear_session after redirect can cause unexpected side effects or errors.
  3. Final Answer:

    The after_action runs even if redirect happens, causing errors -> Option C
  4. Quick Check:

    after_action runs even after redirect [OK]
Hint: after_action runs even if before_action redirects [OK]
Common Mistakes:
  • Assuming after_action skips on redirect
  • Thinking authentication should be after_action
  • Believing private methods must be public
5. You want to run a 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?
hard
A. before_action :check_admin, except: [:edit, :update]
B. before_action :check_admin, only: [:edit, :update]
C. after_action :check_admin, only: [:edit, :update]
D. before_filter :check_admin, only: [:edit, :update]

Solution

  1. Step 1: Identify correct filter type and options

    Use before_action to run code before actions. Use only: to limit to specific actions.
  2. Step 2: Evaluate each option

    before_action :check_admin, only: [:edit, :update] correctly uses before_action with only: [:edit, :update]. before_action :check_admin, except: [:edit, :update] uses except, which excludes those actions. after_action :check_admin, only: [:edit, :update] uses after_action, wrong timing. before_filter :check_admin, only: [:edit, :update] uses deprecated before_filter.
  3. Final Answer:

    before_action :check_admin, only: [:edit, :update] -> Option B
  4. Quick Check:

    Use before_action with only: for specific actions [OK]
Hint: Use before_action with only: to target specific actions [OK]
Common Mistakes:
  • Using except instead of only
  • Using after_action instead of before_action
  • Using deprecated before_filter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard