我正在使用Rails 3.2和Authlogic。我有以下代码:
class ApplicationController < ActionController::Base
private
def store_location
session[:return_to] = request.url
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
end
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => :destroy
def new
@user_session = UserSession.new
@header_title = "Login"
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:success] = "Login successful!"
redirect_back_or_default root_url
else
render 'new'
end
end
def destroy
current_user_session.destroy
flash[:success] = "Logout successful!"
redirect_back_or_default root_url
end
end
此代码非常通用。当我们使用before_filter
:
before_filter :require_user, :only => [:new, :edit, :update, :create]
它将自动store_location
并将我们重定向回正确的页面。但是,我该怎么做:
posts/1
,但require_user
。posts/1
而不是root_url
。答案 0 :(得分:0)
在会话控制器store_location
操作中直接呼叫new
。
# user_sessions_controller.rb
def new
store_location if session[:return_to].blank?
@user_session = UserSession.new
@header_title = "Login"
end
这将首先检查会话哈希中的现有return_to
对。您不希望覆盖它,以防万一,例如,由于密码错误,用户被重定向到new
操作。
如果已从store_location
调用require_user
,也会跳过return_to
。
成功重定向后,您必须从会话哈希中delete # application_controller.rb
def redirect_back_or_default(default)
redirect_to(session.delete(:return_to) || default)
end
对;将其设置为 nil 是不够的:
{{1}}
答案 1 :(得分:0)
我添加了store_referrer_location
以使其正常工作:
# application_controller.rb
class ApplicationController < ActionController::Base
private
def store_referrer_location
session[:return_to] = request.referrer
end
end
# user_sessions_controller.rb
class UserSessionsController < ApplicationController
def new
store_referrer_location if session[:return_to].blank?
@user_session = UserSession.new
@header_title = "Login"
end
...
def destroy
store_referrer_location if session[:return_to].blank?
current_user_session.destroy
flash[:success] = "Logout successful!"
redirect_back_or_default root_url
end
end