当控制器被子类化时,为什么Rails before_filter被调用了两次?

rub*_*eca 13 ruby inheritance ruby-on-rails before-filter actioncontroller

我在Rails 2.3.5,我有这个问题:

class BaseController < ApplicationController
  before_filter :foo, :only => [:index]
end

class ChildController < BaseController
  before_filter :foo, :only => [:index, :show, :other, :actions]
end
Run Code Online (Sandbox Code Playgroud)

问题是在ChildController上,过滤器被调用两次之前的foo.

我已经尝试了很多关于这个问题的解决方法.如果我不在:index孩子中包含该动作,则永远不会调用该动作.

我找到的解决方案有效,但我认为它非常难看

skip_before_filter :foo
before_filter :foo, :only => [:index, :show, :other, :actions]
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来解决这个问题?

Roa*_*ter 15

"此行为是设计使然".

控制器上的Rails指南指出:

"继承过滤器,因此如果在ApplicationController上设置过滤器,它将在应用程序中的每个控制器上运行."

这解释了您所看到的行为.它还建议使用完全相同的解决方案(使用skip_before_filter)来定义将为特定控制器和/或方法运行或不运行哪些过滤器.

所以,丑陋与否,似乎你找到的解决方案是常见且经过批准的实践.

http://guides.rubyonrails.org/action_controller_overview.html#filters