【问题标题】:Namespaces with nested resources Rails 3.2.8具有嵌套资源的命名空间 Rails 3.2.8
【发布时间】:2012-10-02 12:01:28
【问题描述】:

我正在尝试将我的 Rails 应用程序组织到两个提供相同资源但具有不同控制器和视图的命名空间中。类似于以下场景:

routes.rb

resources :beehives do
    resources :bees
    resources :honeycombs
end

namespace :api do
    resources :beehive, only: [:show] do
        resources :bees, only: [:index, :show]
        resources :honeycombs, only: [:index, :show]
    end
end

使用脚手架,我创建了控制器结构:

rails g 控制器 api/蜂箱

rails g 控制器 api/beehives/bees

rails g 控制器 api/beehives/honeycombs

我为控制器获得的文件夹结构听起来像这样:

+ app
  + controllers
    - beehives_controller.rb
    - bees_controller.rb
    - honeycombs_controller.rb
    + api
      - beehives_controller.rb
      + beehives
        - bees_controller.rb
        - honeycombs_controller.rb

controllers/beehives_controller.rb

class Api::BeehivesController < ApplicationController 

controllers/api/beehives_controller.rb

class Api::BeehivesController < ApplicationController 

controllers/api/beehives/bees_controller.rb

class Api::Beehives::BeesController < ApplicationController 

嗯,这很容易。在这种情况下,/beehives/1 将路由到根名称空间(用于 Web 应用程序),/api/beehives/1 将路由到“api”名称空间(用于提供 RESTful Web 服务)。这真的很好。问题是当我尝试访问/api/beehives/1/bees 时,由于某种原因,命名空间不适用于嵌套资源,Rails 吐出这个错误:

uninitialized constant Api::BeesController

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails resources namespaces routes nested


    【解决方案1】:

    resources :beehive + 嵌套的resources :bees 也不需要嵌套您各自的控制器。这只是构建 URL 的一种方式。因此,您的应用自然会请求Api::BeesController 而不是Api::Beehives::BeesController

    如果您有任何疑问,请使用rake routes 命令检查您的路由及其关联的控制器。

    【讨论】:

    • 但是,嘿@jdoe,这破坏了我的文件夹结构。我不得不将相关的控制器放在api 文件夹中,而不是api/beehives。这破坏了我的组织,因为在 api 文件夹中,我将提供多个资源。
    • @DerekWillianStavis resources 接受 :module =&gt; 'behives' 选项。您也可以为嵌套资源使用scope :module =&gt; 'behives' do ... end 包装器。
    • 我认为 :module 不适用于命名空间,但它可以。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2023-03-11
    • 2017-03-17
    相关资源
    最近更新 更多