4

在我的控制器中,我有一个 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
4

2 回答 2

6

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

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
于 2015-02-13T19:05:05.547 回答
0

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

您可以通过条件为 o 回调传递 proc

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

于 2021-07-17T09:58:07.670 回答