ruby on rails -在before_action提前呈现时运行after_action

l7mqbcuq  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(124)

我有一个控制器,我想总是调用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

确保始终调用after_action的最佳方法是什么?目前,只有在实际达到索引操作时才会调用它。
我尝试在after_action的only部分添加:auth

wgeznvg7

wgeznvg71#

after_action callback只有在它所附加的action被执行时才会被调用。如果要确保无论执行哪个操作都始终调用跟踪after_action,则可以在每个操作开始时使用before_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

通过添加before_action:track,track方法将在控制器中的每个动作之前被调用,确保它总是被执行。

相关问题