2014-02-25 35 views
2

我使用Rails 3.2.X爲什麼在子控制器上的before_filters在Rails上的父控制器上之前的過濾器之前被調用?

我有如下控制器繼承情況:

class ApplicationController < ActionController::Base 
    before_filter :do_something 

    protected 

    def do_something 
    end 
end 

class ChildController < ApplicationController 
    before_filter :do_something_else 

    protected 

    def do_something_else 
    end 
end 

ChildController調用動作我看do_something_elsedo_something之前被調用。這是預期的行爲?

即使我做的:

append_before_filter :do_something_else 

do_something_else總是最先調用,這是不是我的預期。

如何在子控制器上定義的before_filters在其父控制器上定義的before_filters之後執行。

[更新]請注意,問題更一般。我需要一個答案,覆蓋ApplicationController之前的任何數量的過濾器以及子控制器和子控制器的子控制器之前的任何數量的過濾器,在較長的繼承樹上。

爲了使這個更新更加清晰:

class ApplicationController < ActionController::Base 
    before_filter :do_something1 
    before_filter :do_something2 
end 

class ChildController < ApplicationController 
    before_filter :do_something3 
    before_filter :do_somethign4 
end 

class Child2Controller < ChildController 
    before_filter :do_something5 
    before_filter :do_somethign6 
end 

Child2Controller呼籲行動應該叫:1)do_something1 2)do_something2 3)do_something3 4)do_something4 5)do_something5 6)do_something6

但他們似乎並沒有被這樣稱呼。

那麼有什麼竅門?

+1

添加評論希望別人不會像我剛纔那樣浪費時間調試。此行爲(父代之前的子過濾器)僅適用於Rails 3.x,這就是問題關閉的原因。至少4.2(可能爲4.0),父過濾器稱爲BEFORE子過濾器。 –

回答

6

相反,嘗試prependApplicationControllerbefore_filter

class ApplicationController < ActionController::Base 
    prepend_before_filter :do_something 

    ... 
end 

有一條關於這個題目這個空間的幾個其他問題。 This one解決了這個問題。

0

如果您希望首先執行該方法,則在ApplicationController中使用prepend_before_filter

class ApplicationController < ActionController::Base 
    prepend_before_filter :do_something 

    protected 

    def do_something 
    end 
end 
+0

我相信這不能回答我的問題。如果我在ApplicationController上有5個before_filters,在子控制器上有5個,會怎麼樣?我應該如何定義它們?以及如果子控制器被另一個控制器類進一步細分,那麼另一個控制器類又有5個before_filters? –

相關問題