【问题标题】:How to use route a controller in and out of namespace in Rails 4如何在 Rails 4 中使用路由控制器进出命名空间
【发布时间】:2014-10-23 22:20:49
【问题描述】:

我是 Rails 新手,有点困惑命名空间的工作原理。基本上我有类别和客户控制器。

我想创建一个管理命名空间(我还不明白),因此某些方法只能通过/admin/products/id, via: 'delete'/admin/... 是重要部分)命名空间访问,而其他方法可以正常访问,如下所示: /products, via: 'get'

如果我理解正确的话,为了创建一个命名空间,我需要创建一个子目录并将控制器放在这个目录中,但我想在这种情况下它将无法正常访问?

这可能吗?怎么样?

我已经尝试过(例如)

match '/admin/products',    to: 'admin#index', via: 'get'

但它给了我一个错误,说一个变量(在模板中)不可用。但是,当我尝试不使用 /admin 时,它运行良好,这意味着问题出在命名空间情况。

【问题讨论】:

  • 您能发布您遇到的确切错误吗?
  • 确切的错误是:undefined method email' for nil:NilClass` 这是由模板触发的(@user 被传递给模板)。传递的参数是: {"id"=>"customers"} 访问 /admin/customers 时告诉我该路由无法识别
  • 查看此链接。它真的帮助我理解了blog.roberteshleman.com/2014/08/14/…

标签: ruby-on-rails ruby-on-rails-4 namespaces


【解决方案1】:

namespace 等同于您的控制器的模块。

简单地说,您必须执行以下操作:

  • 将命名空间控制器放入同名的子目录中
  • 您的所有路由都需要通过命名空间助手发送

这是如何做到这一点的:


命名空间

阅读namespacing from the Rails documents,您将处于最佳位置

如果你想创建一个“admin”命名空间,你可以执行以下操作(我们使用这个):

#config/routes.rb
namespace :admin do
   root "products#index"

   resources :products, only: [:new, :create]
   resources :customers, only: [:new, :create]
end

resources :products, only: [:index, :show]
resources :customers, only: [:index, :show]

这将为您创建许多路线;但命名空间的只会提供

以下是构建控制器的方法:

#app/controllers/admin/application_controller.rb
class Admin::ApplicationController < ActionController::Base
   before_action :authenticate_user!
end

#app/controllers/admin/products_controller.rb
class Admin::ProductsController < Admin::ApplicationController
   def index
      @products = Product.all
   end
end

这将为您提供一个仅限身份验证的区域,以提供对创建 ProductCategory 对象的访问权限。

如果你想路由到这些控制器,你需要使用提供的命名空间路由:

<%= link_to "New Product", admin_product_path if user_signed_in? %>

【讨论】:

  • 不幸的是,这也不起作用。我一个字母一个字母地复制了你的代码,尝试了一些小的变化,但总是得到同样的错误:未定义在我的控制器中定义的变量(因为未达到该方法)并且参数是 admin :id => categories这意味着 Rails 将 /admin/categories 中的 categories 视为参数而不是路由。另外,我正在使用带有 Mongoid 的 Rails 4。这有什么区别吗?
【解决方案2】:

如果您将以下命名空间添加到您的route.rb

namespace :admin do
  resources : categories
  resources : customers
end

您可以在controllers/admin 文件夹中创建以下控制器:

#base_controller.rb - will work like your application_controller for the namespace
class Admin::BaseController < ActionController::Base
  ...
end

#categories_controller.rb - will work like your categories_controller for the namespace
class Admin::CategoriesController < Admin::BaseController
  ...
end

#customers_controller.rb - will work like your customers_controller for the namespace
class Admin::CustomersController < Admin::BaseController
  ...
end

通过这种方式,您可以在基本控制器中添加身份验证,为管理员提供完全访问权限,并从非命名空间部分中删除 deleteedit 等操作。

希望对你有帮助……

【讨论】:

  • 不幸的是它没有用。路线无法识别,我得到了同样的错误
猜你喜欢
  • 2015-07-05
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多