在Rails中,如何在管理部分中有/ admin部分,然后是控制器?

我想在我的应用程序中有一个/ admin部分,并在此/ admin部分中有路由,如:

www.example.com/admin/(只有某些用户可以访问此部分)

然后在本节中有控制器,如:

/admin/users/{add, new, etc} 

对于这样的事情我有什么选择? (使用导轨3)

在您的routes.rb中执行类似的操作:

  namespace :admin do resources :users end 

有关更多详细信息,请参见http://guides.rubyonrails.org/routing.html 。

然后在每个管理控制器中,您将需要一个before_filter:

 before_filter :authorized? def authorized? #check if authorized here. end 

我喜欢做类似托德的回答,但略有不同。 而不是将before_filter添加到与Admin内容相关的每个控制器,我更喜欢创建一个AdminController,所有与管理操作相关的控制器都可以inheritance自:

 # config/routes.rb namespace :admin do resources :users end # app/controllers/admin_controller.rb class AdminController < ApplicationController before_filter :authorized? private def authorized? unless current_user.has_role? :admin flash[:error] = "You are not authorized to view that page." redirect_to root_path end end end # app/controllers/admin/users_controller.rb class Admin::UsersController < AdminController ... end 

正如Todd所说,你想添加一个命名空间的路由:

 namespace :admin do resources :users end 

您还需要将控制器,视图等放在名为“admin /”的每个部分的子文件夹中。 如果你从头开始生成这个,很容易:

 rails g controller admin/users 

这可能看起来相当复杂,但我有一篇文章介绍了所有这些,你可以下载一个示例rails 3应用程序来玩它:

Ruby on Rails中的路由3

然后在每个管理控制器中,您将需要一个before_filter:

 before_filter :authorized? def authorized? #check if authorized here. end 

我认为如果他把这个代码放到一个inheritance自ApplicationController的主AdminController中会更好,那么每个管理控制器都会inheritance这个AdminController。

关于Rails3, 这是一篇关于路线的好文章

显然托德所说的是正确的。 但是,如果您是通过默默无闻的额外安全性的粉丝,您还可以保留new_admin_user url帮助程序和Admin:: namespaced控制器,但提供不太广泛使用的公共URL路径,其中包含以下内容:

 scope :module => "admin", :as => 'admin', :path => 'xyz' do resources :user end 

具有该设置的rake route将显示沿这些线的路线:

 new_admin_user GET /xyz/users/new(.:format) {:controller=>"admin/users", :action=>"new"} 

我认为唯一能阻挠的是一个不成熟的攻击者,他抓取并编译了一堆Rails站点,这些站点在admin/中提供系统访问权限,但我认为与你的管理控制台路径不同,我觉得没什么坏处。

 application_controller.rb before_filter :if_namespace_is_admin? def if_name_space_is_admin? #now you should check to see if the namespace is from admin #now you need namespaces because ruby ns confuse the f'out of me end