【问题标题】:Rails: prepend_before_action in superclassRails:超类中的 prepend_before_action
【发布时间】:2016-02-22 18:01:45
【问题描述】:

我的 ApplicationController 中有一个身份验证方法,我总是想首先运行它。我在子控制器中也有一个方法,我想在身份验证方法之后但在其他 ApplicationController before_actions 之前运行它。换句话说,我想要这个:

ApplicationController
before_action first
before_action third

OtherController < ApplicationController
before_action second

上述导致方法按以下顺序调用:first -> third -> second。 但我想要订单:first -> second -> third

我尝试过使用 prepend_before_action,如下所示:

ApplicationController
prepend_before_action first
before_action third

OtherController < ApplicationController
prepend_before_action second

但这会导致它运行second -> first -> third

如何让订单成为first -> second -> third

【问题讨论】:

    标签: ruby-on-rails controller before-filter operator-precedence


    【解决方案1】:

    您可以像这样使用prepend_before_action

    class ApplicationController < ActionController::Base
      before_action :first
      before_action :third
    end
    
    class OtherController < ApplicationController
      prepend_before_action :third, :second
    end
    

    【讨论】:

    • Rails 以完全相同的方式处理prepend_before_actionbefore_action 的参数——你能解释一下为什么会这样吗?看起来它最终会调用两次:third
    【解决方案2】:

    尝试以下方法,看看是否有效:

    class ApplicationController < ActionController::Base
      before_action :first
      before_action :third
    end
    
    class OtherController < ApplicationController
      skip_before_action :third
      before_action :second
      before_action :third
    end
    

    【讨论】:

    • 不幸的是,在我的所有子类中,我必须添加这个解决方法。我希望有某种方法可以修改 ApplicationController 以实现结果。
    • 如果它在您的大多数控制器中,您可以在父级中运行 :second_action 并在少数子级中跳过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多