Rails 3 - 重定向登录用户

时间:2011-05-31 12:36:25

标签: ruby-on-rails ruby-on-rails-3 devise

我正在为我的社区博客使用Devise和Can-Can,并且正在寻找一种方法,一旦他们登录,就可以直接将“管理员和版主”直接重定向到views / admin / index页面。不确定是否我可以在routes.rb或登录表单中执行此操作吗?任何帮助表示赞赏...

application_controller

class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
flash[:alert] = exception.message
redirect_to root_url
end
end

routes.rb文件

root :to => "articles#index"

节/ new.html.erb

<h2>Sign In</h2>

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>

<p><%= f.label :email %><br />
<%= f.text_field :email %></p>

<p><%= f.label :password %><br />
<%= f.password_field :password %></p>

<% if devise_mapping.rememberable? -%>
<p><%= f.check_box :remember_me %> <%= f.label :remember_me %></p>
<% end -%>

<p><%= f.submit "Sign In" %></p>
<% end %>

错误

NoMethodError in Devise/sessionsController#create - 

Application Trace | Framework Trace | Full Trace
app/controllers/application_controller.rb:11:in `after_sign_in_path_for'

1 个答案:

答案 0 :(得分:2)

application_controller中添加以下内容:

class ApplicationController < ActionController::Base

  def after_sign_in_path_for(resource)
    if current_user.role?("admin") or current_user.role?("moderator")
      admins_index_path    # Make sure this route exists in your app!
    else
      stored_location_for(:user)
    end
  end

end

替代方案(适用于Devise 1.1.x):

class ApplicationController < ActionController::Base

  def stored_location_for(resource)
    if current_user && (current_user.role?("admin") || current_user.role?("moderator"))
      return admin_index_path    # Make sure this route exists in your app!
    end
    super(resource) 
  end

end