我正在嘗試使用過濾器來阻止未經認可的用戶訪問頁面。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上看到的答案。
你是否嘗試過使用會話中的'id'而不是將它作爲參數傳遞給過濾器?這樣sintax就只是'before_filter:check_user_for_current_approval,:only => [:new]'。 –
我想弄清楚如何使用調用具有參數的方法的before_filter。答案提供了一種適用於所有方法的解決方案,而不僅僅是一種可以從內部調用current_user.id的方法。 – EastsideDeveloper