ruby on rails - Running an after_action when a before_action renders early

79 views Asked by At

I have a Controller where I want to always call an after_action

before_action :auth
after_action :track, only [:index]

def index 
 render json: ..., status: 200
end

def show
...
end

def auth
 return if some_condition
 render json: ..., status 422
end

def track 
 status = response.status if response.successful?
 # do something with status
end 

What is the best way to ensure the after_action is always called? Currently it is only called if the index action is actually reached.

I've tried adding :auth to the only section of the after_action

1

There are 1 answers

0
Waleed Bin Tariq On

after_action callback will only be called if the action it is attached to is executed. If you want to ensure that the track after_action is always called, regardless of which action is executed, you can use a before_action to call it at the beginning of each action

before_action :auth
before_action :track

def index 
  render json: ..., status: 200
end

def show
  # ...
end

def auth
  return if some_condition
  render json: ..., status: 422
end

def track 
  status = response.status if response.successful?
  # do something with status
end 

By adding before_action :track, the track method will be called before every action in your controller, ensuring that it is always executed.