2012-10-25 21 views
0

我正在嘗試使用過濾器來阻止未經認可的用戶訪問頁面。Rails:從帶有自變量的過濾器調用函數

爲了檢查非批准的用戶,我在.RB文件中定義的方法中,在/ lib文件夾(I有幾種方法有,我是在各種控制器和視圖)。該方法是check_user_for_current_approval(user_id)。

在我的控制,我試過以下變化(請注意,我用的RubyMine作爲一個IDE,並沒有給我的指示,我有一個語法錯誤):

before_filter(:only => [:new]) do |c| 
    c.check_user_for_current_approval current_user.id 
end 

這給了我以下錯誤消息:

NoMethodError in PaymentsController#new 

private method `check_user_for_current_approval' called for #<PaymentsController:0x007ff06784f148> 

以下語法:

before_filter(:only => [:new]) do |c| 
    c.send (:check_user_for_current_approval, current_user.id) 
end 

機生產線CES這個錯誤:

SyntaxError in PaymentsController#new 

/app/controllers/payments_controller.rb:9: syntax error, unexpected ',', expecting ')' 
c.send (:check_user_for_current_approval, current_user.id) 
             ^
/app/controllers/payments_controller.rb:9: syntax error, unexpected ')', expecting keyword_end 
/app/controllers/payments_controller.rb:130: syntax error, unexpected $end, expecting keyword_end 

使用這個語法:

before_filter(:only => [:new]) { check_user_for_current_approval(current_user.id) } 

帶我直接到頁面(過濾器沒有任何影響)。不同的陳述來自於我在StackOverflow上看到的答案。

+0

你是否嘗試過使用會話中的'id'而不是將它作爲參數傳遞給過濾器?這樣sintax就只是'before_filter:check_user_for_current_approval,:only => [:new]'。 –

+0

我想弄清楚如何使用調用具有參數的方法的before_filter。答案提供了一種適用於所有方法的解決方案,而不僅僅是一種可以從內部調用current_user.id的方法。 – EastsideDeveloper

回答

1

使用你的第一種方法,但使check_user_for_current_approval公開。

另外:

我想共享before_filter會更適合於應用控制器,而不是在一個lib文件。 這樣可以讓所有擴展應用程序控制器的控制器都可以訪問它,這通常是所有其他控制器所做的。

+0

宣佈它公開工作。你的意思是將check_user_for_current_approval方法放在應用程序控制器中?這也是我在某些視圖中使用的方法。 – EastsideDeveloper

0

爲什麼不使用符號來定義要調用的方法?

例如PaymentsController:

before_filter :check_user_for_current_approval, :only => :new 

def check_user_for_current_approval; raise "Called"; end 
+0

我不認爲我理解你的答案。這不會讓我傳遞參數給方法。 – EastsideDeveloper