author avatar

nitturu.baba

Mon Oct 28 2024

before_action runs a specified method before the controller action. It’s useful for tasks that need to happen before executing the main action, such as authentication, setting up a resource, or ensuring permissions.


after_action runs a specified method after the controller action has executed. It’s useful for tasks that need to happen after the response is rendered, such as logging activity, tracking metrics, or cleaning up resources.




class PointsController < ApplicationController
  before_action :set_user_points, only: [:show, :redeem]
  after_action :update_points_history, only: [:redeem]

  def show
    # Show points balance
  end

  def redeem
    # Redeem points logic
  end

  private

  def set_user_points
    @points = current_user.points
  end

  def update_points_history
    # Log the points redemption action
  end
end



In the above example set_user_points will execute before the controller actions show and redeem. update_points_history will execute after the redeem action.

#CU6U0R822