我在Rails 3中使用Devise。如果未登录的用户点击链接,我已使用before_filter :authenticate_user!
重定向登录。这有效,但登录后,它会重定向回主页。相反,我想重定向到用户在重定向到登录页面之前单击的链接。这是我的代码:
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_user!
layout :layout_by_resource
def after_sign_in_path_for(resource_or_scope)
if resource_or_scope.is_a?(User)
if current_user.admin?
admin_event_types_path
else
home_path
end
else
super
end
end
..
..
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:token_authenticatable
..
..
end
更新
我使用@dreamfall的回答尝试了这个,但它没有按预期重定向。
def after_sign_in_path_for(resource_or_scope)
if resource_or_scope.is_a?(User)
if current_user.admin?
stored_location_for(resource_or_scope) ? stored_location_for(resource_or_scope) : admin_event_types_path
else
stored_location_for(resource_or_scope) ? stored_location_for(resource_or_scope) : home_path
end
else
super
end
end
Devise中是否有内置配置?如果没有,我将如何解决这个问题?我应该在哪里更改代码?
答案 0 :(得分:1)
Devise提供了在登录后重定向到存储在会话网址中的功能。在stored_location_for(resource_or_scope)
方法中使用after_sign_in_path_for(resource_or_scope)
方法。
答案 1 :(得分:0)
我遇到了同样的问题,我解决了这个问题:
before_action :store_location
def after_sign_in_path_for(*)
session[:previous_url] || root_path
end
private
def store_location
# store last url - this is needed for post-login redirect to
whatever the user last visited.
return unless request.get?
if (request.path != "/users/sign_in" &&
request.path != "/users/sign_up" &&
request.path != "/users/password/new" &&
request.path != "/users/password/edit" &&
request.path != "/users/confirmation" &&
request.path != "/users/sign_out" &&
!request.xhr?) # don't store ajax calls
session[:previous_url] = request.fullpath
end
end
这基本上是拦截所有获取请求并将URL保存在用户的会话上。在您登录后如果保存了previous_url,它将被正确重定向。