【问题标题】:Routing errors when adding an Admin namespace添加 Admin 命名空间时出现路由错误
【发布时间】:2011-11-26 04:08:06
【问题描述】:

我在我的应用中添加了一个 Admin 命名空间,所以当登录到管理区域时,它必须是这样的:admin/websites 和 admin/page/8

这就是我在 routes.rb 中的内容

namespace :admin do |admin|
  match '/' => 'dashboard#index'
  resources :websites
  resources :pages
  resources :sessions
  get 'login' => 'sessions#new', :as => 'login'
  get 'logout' => 'sessions#destroy', :as => 'logout'  
end

我在 app/controllers 目录中有 admin_controller.rb。

class Admin::BaseController < ApplicationController
  protect_from_forgery
  include UrlHelper
  ...

我在 app/controllers 中创建了一个管理目录。所以我在 app/controllers/admin/websites_controller.rb 里面有这个

class Admin::WebsitesController < ApplicationController

其他一些答案建议类 Admin::WebsitesController

那么在我的布局文件 (app/views/layouts/application.html.erb) 中,我有这样的链接 edit_admin_website_path(@website) 给我路由错误 Routing Error No route matches {:action=&gt;"edit", :controller=&gt;"admin/websites"}Whyyyy?! :(

【问题讨论】:

  • 这个错误返回的 url 选项通常应该是 {:action=&gt;"edit", :controller=&gt;"admin/websites", :id =&gt; 3} 或任何 id,你能检查一下:@website 不是 nil 并且 @website 是持久的(不是 new_record?
  • 你使用的是什么版本的 Rails?
  • 一个巧妙的技巧:如果您发现edit_admin_website_path(@website) 过于冗长,您可以使用(至少对于 url / 链接助手):[:edit, :admin, @website]
  • 你是对的!我对 application_controller 进行了更改,并且不再加载 @website。所以我刚刚创建了一个 current_website 辅助方法并在 edit_admin_website_path 上使用它,就像这样 edit_admin_website_path(current_website) 非常感谢! :D

标签: ruby-on-rails ruby namespaces routes


【解决方案1】:

在 admin 目录中添加一个名为 application_controller.rb 的文件,其中包含以下内容:

class Admin::ApplicationController < ApplicationController
end

然后,对于此目录中的每个控制器,扩展 Admin::ApplicationController 类。

你试过了吗?

admin_edit_website_path(@website)

【讨论】:

  • 我比我更喜欢这个答案。 :)
  • 抱歉路径,我在控制器中进行了更改,@website 不再被加载。所以我刚刚创建了一个名为 current_website 的所有控制器都可以使用的帮助方法,并将其编码为 admin_edit_website_path(current_website)
  • 为什么认为这种方法更好?
  • @leonel,它只是更整洁的组织,controllers/admin 文件夹的结构与其父文件夹的结构相同。基类仍然叫ApplicationController,只是命名空间发生了变化……
【解决方案2】:

Rails 命名空间依赖于文件夹结构来加载正确的类。你应该像这样构造它:

app/controllers
  admin_controller.rb # class AdminController < ApplicationController

app/controllers/admin
  websites_controller.rb # class Admin::WebsitesController < AdminController

AdminController 应该在 admin 文件夹之外定义。如果把它放在那里,你必须将它称为Admin::AdminController,这有点奇怪。实际上,您可以将其称为 AdminNamespaceController 以明确。

您也可以使用rails generate,它会在预期的位置为您设置好东西,尽管我认为它不会创建命名空间基类供您继承。

【讨论】:

    猜你喜欢
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2016-11-12
    • 2012-02-20
    • 2012-05-01
    • 1970-01-01
    相关资源
    最近更新 更多