对于我正在编写的应用程序,我使用简单的手工身份验证(如Railscast.com上所述)。使用Ryan Bates的NiftyGenerators gem中的一些代码,我有一个身份验证模型,它有一些有用的身份验证方法。该模块包含在application_controller.rb
中。
我想要使用的方法之一称为redirect_to_target_or_default
。我知道这是我需要将用户重定向到他们经过身份验证后所在的页面,但我不知道应该在哪里调用此方法?如果有人能给我一个如何使用这种方法的想法,我将非常感激。
ControllerAuthenticaion模块代码
module ControllerAuthentication
# Makes these methods helper methods in the controller that includes this module.
def self.included(controller)
controller.send :helper_method,
:current_admin, :logged_in?,
:redirect_to_target_or_default
end
def current_admin
@current_admin ||= Admin.find(session[:admin_id]) if session[:admin_id]
end
def logged_in?
current_admin
end
def login_required
unless logged_in?
store_target_location
redirect_to login_url,
:alert => "You must first log in before accessing this page."
end
end
def redirect_to_target_or_default(default, *args)
redirect_to(session[:return_to] || default, *args)
session[:return_to] = nil
end
def redirect_to_or_default(target, *args)
redirect_to(target || default, *args)
end
def store_target_location
session[:return_to] = request.url
end
end
答案 0 :(得分:3)
你是否在Ryan的宝石中运行了发电机?它应该为你生成一个SessionController(参考link),同时也包含这个方法:
def create
@session = Session.new(params[:session])
if @session.save
flash[:notice] = "Logged in successfully."
redirect_to_target_or_default(root_url)
else
render :action => 'new'
end
end
我认为您可以在阅读此代码时了解如何使用它。 :)