[英]A controller before_filter has no effect
在Rails 4中,我使用before_action :require_login
作為我的UserController
。 如果用戶未登錄,則應該重定向。但是似乎沒有使用過濾器。 為什么?
require_login
在app/helpers/sessions_helper.rb
定義。 所以它不是我的控制器UsersController的幫手。
UserController
如何知道如何使用sessions_helper.rb
的函數? 看起來我應該更具體: before_action "session/require_login"
。
users_controller.rb中的控制器:
class UsersController < ApplicationController
before_action :signed_in_user
def index
end
end
sessions_helper.rb中的輔助函數:
def require_login
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
end
您正在關注Michael Hartl的教程? 設計用於視圖邏輯的/ app / helper中的助手,而不是用於控制器代碼。
但是,要將幫助程序包含在控制器中,可以使用include SessionsHelper
。
參考: http : //ruby.railstutorial.org/chapters/sign-in-sign-out#code-sessions_helper_include
before_filter
只能調用controller方法,而不是helper。
您需要將幫助程序require_login
從幫助程序移動到UsesController或其父級說ApplicationController。
如果您仍希望在視圖中使用require_login
作為幫助程序,則可以通過helper_method
從控制器中公開它
class UsersController < ApplicationController
before_fitler :require_login
helper_method :require_login
def require_login
# code
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.