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 が 2 回呼び出されることです。

この問題を回避する方法をいくつか試しました。子にアクションを含めない:indexと、そのアクションに対して呼び出されることはありません。

私が見つけた解決策は機能しますが、非常に醜いと思います

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

この問題を解決するより良い方法はありますか?

4

2 に答える 2

15

"This behavior is by design".

The Rails guide on controllers states:

"Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application."

This explains the behaviour you're seeing. It also suggests the exact same solution you propose (using skip_before_filter) to define which filters will or will not be run for a particular controller and/or methods.

So, ugly or not, seems like the solution you found is common and approved practice.

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

于 2010-05-24T16:27:28.080 に答える
3

使用したくない場合は、次のアクションをskip_before_filterいつでもスキップできます。indexChildController

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

ただし、動作を変更してアクションBaseControllerからフィルターを削除すると、これが問題になる可能性があります。indexその後、それは決して呼び出されないので、使用skip_before_filterする方が良い考えかもしれません.

于 2010-05-24T18:54:04.897 に答える