我試圖將我的Rails應用程序組織到兩個提供相同資源但具有不同控制器和視圖的命名空間中。像下面cenario:具有嵌套資源的命名空間Rails 3.2.8
的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 controller api/beehives
rails g controller api/beehives/bees
rails g controller api/beehives/honeycombs
的文件夾結構我得到了控制器聽起來像此:
個控制器/ beehives_controller.rb
class Api::BeehivesController < ApplicationController
控制器/ API/beehives_controller.rb
class Api::BeehivesController < ApplicationController
控制器/ API /蜂箱/ 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
我做錯了嗎?
它的工作。謝謝! – derekstavis
但嘿@jdoe,這打破了我的文件夾結構。我不得不把相關的控制器放在'api'文件夾中,而不是'api/beehives'。這打破了我的組織,因爲在'api'文件夾中,我將有多個資源提供。 – derekstavis
@DerekWillianStavis'resources'接受':module =>'behives''選項。你也可以使用'scope:module =>'behives'do ... end'封裝你的嵌套資源。 – jdoe