rails 跳过控制器/方法中的 after_action

Dan*_*iel 4 controller ruby-on-rails ruby-on-rails-4.2

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

导轨 4.2,红宝石 2.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
Run Code Online (Sandbox Code Playgroud)

inf*_*sed 5

我会这样做。如果 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
Run Code Online (Sandbox Code Playgroud)