2010-02-12 35 views
0

假設require_role ["alt", "student worker"], :except => [:list, :show, :index, :create]工作在這種方法之外,我在這裏做錯了什麼?當我調用它的方法時,它是一個promo_site? (true),但是當它是false時,該方法失敗。簡單的紅寶石,除非方法錯誤,ROR

def check_if_role_is_required 
    require_role ["alt", "student worker"], :except => [:list, :show, :index, :create] unless promo_site? 
    end 
+1

在約翰尼拉5的話說:「需要更多的投入「。代碼位於您的應用程序中的哪個位置?哪種方法會給你一個錯誤?什麼是錯誤? – EmFi 2010-02-12 05:33:40

回答

1

曖昧的問題,所以這僅僅是猜測:

在它看起來像require_role一看是一個的before_filter的包裝。所以我要根據這個觀察結果來回答我的觀點。

before_filter是一個控制器類的方法。與check_if_role_required相反,它似乎是一個控制器實例方法。因爲require_role看起來是before_filter的包裝器,所以我會假設這也是一個類方法。

當您調用裸方法(未由對象調用)時,Ruby會隱式確定調用對象爲self。這可以成爲方法調用的外部方法的定義類,或調用其他方法內的方法調用的當前方法的對象。在類方法的情況下,self是當前類。當涉及到before_filter時,它預計會被ActionController :: Base類調用。通過在實例方法(如check_if_role_required)中調用它,自我評估爲ActionController :: Base的實例,該實例沒有before_filter或可能甚至require_role定義。

代碼總是有助於水泥的例子:

這個簡單的類可以幫助說明我的觀點。

class Example 

    # class method like required_role or before_filter 
    def self.c_method 
    # calls self.class 
    # self is the class Example 
    class 
    end 

    c_method # valid statement 

    #instance method like check_if_role_required 
    def i_method 
    #calls self.class 
    # self is an instance of the Example class. 
    class 
    end 

    # invalid statement 
    # i.method 

    def missing_method_example 
    # raises error. 
    # calls self.c_method, but self is the instance. 
    # c_method is not defined for instances of Example 
    c_method 
    end 
end 

Example.c_method # => "Class" 
@example = Example.new 
@example.i_method # => "Example" 
@example.missing_method_example # => Unknown Method Error 
+0

這導致我正確的答案:我打電話給before_filter:check_if_role_is_required,我刪除了before_filter調用,我的方法工作。謝謝 – 2010-02-13 19:24:46

0

嘗試來包裝你的參數在括號:

require_role(["alt", "student worker"], :except => [:list, :show, :index, :create]) unless promo_site?

這通常能解決其中的哈希涉及此類問題...