在 Rails 2.3 的库 Devise 1.0 中有没有办法在登录后重定向到特定的 URL 而不是 root_url?
编辑:忘了提到它的设计 1.0
在 Rails 2.3 的库 Devise 1.0 中有没有办法在登录后重定向到特定的 URL 而不是 root_url?
编辑:忘了提到它的设计 1.0
很有可能您的用户在after_sign_in_path被调用之前就被重定向了。如果用户尝试直接访问受身份验证保护的页面,则会发生这种情况。如果您的root_path('/') 受身份验证保护,这将一直发生。
谷歌群组上有关于这个话题的讨论:
快速而肮脏的解决方案是覆盖stored_location_for以始终返回nil,如下所示:
class ApplicationController < ActionController::Base
...
private
def stored_location_for(resource_or_scope)
nil
end
def after_sign_in_path_for(resource_or_scope)
my_favorite_path
end
end
我认为after_sign_in_path_forDevise 中的方法是您正在寻找的。
在 ApplicationController 中定义该方法,它将覆盖 Devise 的默认实现。这是文档指定要做的事情。
假设您想在登录后显示用户的仪表板。
class HomesController < ApplicationController
def index
if current_user //returns nil if not logged in
@users = User.all
render :dashboard
end
end
def dashboard
@users = User.all
end
end
在 routes.rb 中:
root :to => 'homes#index'
如果已登录,则在 index 操作中输入 if-block 并呈现dashboard.erb。(确保在 if 块中初始化 dashboard.erb 所需的所有变量)否则 rails 会渲染 index.erb