5

通过使用 Devise 进行身份验证和 CanCan 进行授权的 Rails_Admin 标准安装,以非管理员用户身份访问http://localhost:3000/admin会产生以下服务器日志:

Started GET "/admin" for 127.0.0.1 at 2011-08-09 22:46:10 -0400
  Processing by RailsAdmin::MainController#index as HTML
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Completed 404 Not Found in 151ms

ActionController::RoutingError (No route matches {:controller=>"gyms"}):
  app/controllers/application_controller.rb:5:in `block in <class:ApplicationController>'

直到最后一部分的一切似乎都还好。据我所知,CanCan 正确地挽救了异常并尝试通过以下代码重定向到 root_url:

class ApplicationController < ActionController::Base
  protect_from_forgery

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end

TopOut::Application.routes.draw do
  mount RailsAdmin::Engine => '/admin', :as => 'rails_admin'
  devise_for :users

  resources :gyms

  root :to => "gyms#index"
end

但是由于某种原因,在重定向到 root_url 时,CanCan 只是试图命中

{:controller=>"gyms"}

而不是

{:controller=>"gyms", :action=>"index"}

这可能是CanCan的问题吗?还是我在文档中遗漏了 redirect_to 或 root_url 的某些特定方面?

注意:这是我在 CanCan 的 github 页面上打开的一个问题的副本,所以如果另一个问题得到解决,我一定会关闭一个。

4

1 回答 1

6

根据 Github 用户的反馈,路由似乎是 name_scoped 的,因此这是预期的行为。

正确的解决方法是从 main_app 调用 root_url,如下所示:

rescue_from CanCan::AccessDenied do |exception|
  redirect_to main_app.root_url, :alert => exception.message
end

该解决方案的功劳归于 bbenezech,网址为https://github.com/sferik/rails_admin/issues/658

于 2011-09-12T15:35:43.390 回答