Rails 控制器中 before_filters 的顺序和问题

order of before_filters in Rails controller and concerns

我有一个 Rails 问题定义如下:

module MyConcern
  extend ActiveSupport::Concern

  included do
    before_filter :filter_inside_concern
  end

  def filter_inside_concern
    # ...
  end
end

而且我在控制器层上也有一个 before_filter:

class MyController < ApplicationController
  before_filter :filter_inside_controller
end

如果我在 MyController 中包含 MyConcern,调用前置过滤器的顺序是否取决于代码的排列方式?例如,如果我们有

class MyController < ApplicationController
  include MyConcern

  before_filter :filter_inside_controller
end

filter_inside_concern 是否在 filter_inside_controller 之前被调用(反之亦然)?

谢谢!

我重现了您的情况,发现执行顺序取决于您编写两个过滤器的顺序。

如果你写

  include MyConcern
  before_filter :filter_inside_controller

关注过滤器将首先执行

或者如果您按此顺序编写过滤器

  before_filter :filter_inside_controller
  include MyConcern

控制器过滤器将首先执行

如果您使用:

class MyController < ApplicationController
  include MyConcern

  before_filter :filter_inside_controller
end

filter_inside_concern 将在 filter_inside_controller

之前被调用

如果要在 filter_inside_concern 之前调用 filter_inside_controller,则需要使用 prepend_before_filter

class MyController < ApplicationController
  include MyConcern

  prepend_before_filter :filter_inside_controller
end

作为旁注,before_filterprepend_before_filter 将被弃用。您应该改用 before_actionprepend_before_action