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

13

我使用的是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
问题在于在ChildController中,:foo 过滤器会被调用两次。
我尝试了很多解决方法。如果我不在子类中包含 :index 操作,它在该操作上就不会被调用。
我找到的解决方案有效,但我认为它非常丑陋。
skip_before_filter :foo
before_filter :foo, :only => [:index, :show, :other, :actions]

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

2个回答

15

"这是预期的行为"。

关于控制器的Rails指南声明:

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

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

因此,无论丑陋与否,似乎像您找到的解决方案是常见且可接受的做法。

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


3

如果您不想使用skip_before_filter,您可以始终跳过ChildController中的index操作:

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

但是如果您更改BaseController中的行为并从index操作中删除过滤器,则可能会出现问题。那么它将永远不会被调用,因此使用skip_before_filter可能是一个更好的选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接