Consider this Rails controller snippet. What will be printed when the show action is called?
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
Remember that before_action runs the method before the action method.
The before_action :set_article runs before show, so @article is set. The show action renders the title "Hello World".
Given these Rails controller callbacks, which one runs after the action method?
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
Think about which callback runs after the controller action finishes.
The after_action callback runs after the action method completes, so log_action runs after index.
Examine this Rails controller code. What error will it raise when loaded?
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
Consider how params is available in controller methods.
The params method is available in controller instance methods, so set_product can call Product.find(params[:id]) without error.
In this Rails controller, will the after_action callback run?
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
Redirects do not prevent after_action callbacks from running.
after_action callbacks are executed after the action method completes execution, regardless of whether the action performed a render or a redirect.
Given these callbacks in a Rails controller, what is the correct order they run when an action is called?
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
Remember that around_action wraps the action and other callbacks.
The before_action runs first, then the around_action starts and yields to the action, then the around_action ends, and finally the after_action runs.