rails 在 controller/method 中跳过 after_action

rails skip an after_action in a controller/method

在我的控制器中,我有一个 after_action 块。当相关方法失败时,我想从 运行 停止 after_action。

Rails4.2,ruby2.2

有人知道如何在 rails 中执行此操作吗?

class MyController  < ApplicationController

  after_action only: :show do
    # do so and so
  end

  def show
    begin
      # something really bad happens here... My Nose!

    rescue => e 

      # how do I stop after_action from running?

      flash[:error] = 'Oh noes... Someone make a log report'
      redirect_to '/'
      return
    end

    # yarda yarda yarda

  end
end

我会这样做。如果 show 操作错误并在之后的操作中检查该变量,请设置一个实例变量:

class MyController  < ApplicationController

  after_action only: :show do
    unless @skip_after_action
      # after action code here
    end
  end

  def show
    begin
      # something really bad happens here...
    rescue => e 
      @skip_after_action = true
      flash[:error] = 'Oh noes... Someone make a log report'
      redirect_to '/'
    end
  end
end

来自对这些文档的评论https://apidock.com/rails/AbstractController/Callbacks/ClassMethods/after_action

You can pass an proc for o callback with the conditions

after_action :initial_value, only: [:index, :show], unless: -> { @foo.nil? }

after_action :initial_value, only: [:index, :show], if: -> { @foo }

还有https://apidock.com/rails/v6.1.3.1/AbstractController/Callbacks/ClassMethods/skip_after_action