【问题标题】:rails skip an after_action in a controller/methodrails 跳过控制器/方法中的 after_action
【发布时间】:2023-03-17 02:38:01
【问题描述】:

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

Rails 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

【问题讨论】:

  • 为什么不创建一个函数并在 show(action) 方法中使用条件调用它。
  • 我删除了它,但我在 :show 上使用了动作缓存。
  • 浏览文档,你不可能有条件回调一个动作。我想你必须在你的回调块中加入一些逻辑。否则等待更好的意见。

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


【解决方案1】:

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

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

【讨论】:

  • 接缝是镇上唯一的选择。 :(
【解决方案2】:

来自对这些文档的评论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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多