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

时间:2015-02-13 18:04:53

标签: ruby-on-rails controller ruby-on-rails-4.2

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

Rails 4.2,ruby 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

2 个答案:

答案 0 :(得分:3)

我会这样做。如果显示操作错误,请设置实例变量,并在after操作中检查该变量:

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

答案 1 :(得分:0)

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

<块引用>

您可以通过条件为 o 回调传递一个过程

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