13

我在Rails的2.3.5,我有这样的问题:为什么Rails before_filter在控制器被子类化时调用两次?

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

class ChildController < BaseController 
    before_filter :foo, :only => [:index, :show, :other, :actions] 
end 

的问题是,在ChildController的:过滤器之前FOO被调用两次。

我已经尝试了一些解决此问题的解决方法。如果我不在孩子中包含:index操作,它将永远不会被请求执行该操作。

的解决方案,我发现的作品,但我认为这是非常非常难看

skip_before_filter :foo 
before_filter :foo, :only => [:index, :show, :other, :actions] 

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

回答

15

“这种行为是通过设计的”。

控制器上的Rails的指南指出:

“过滤器是继承的,因此,如果您设置的ApplicationController一个过滤器,它会在你的应用程序中每个控制器上运行”

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

因此,看起来像你找到的解决方案是常见的和批准的做法。

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

3

如果你不想使用skip_before_filter你总是可以跳过在ChildControllerindex行动:

class ChildController < BaseController 
    before_filter :foo, :only => [:show, :other, :actions] 
end 

但是,如果你在BaseController改变行为,这可能会成为一个问题,从index操作中删除过滤器。那么它永远不会被称为使用skip_before_filter可能是一个更好的主意。

相关问题