2013-03-20 65 views
2

我無法爲我的控制器創建一個模塊,並讓我的路線指向控制器內的那個模塊。Rails路由和控制器模塊 - 名稱間隔?

收到此錯誤:

Routing Error 
uninitialized constant Api::Fb 

所以,這是我的路線是如何設置:

namespace :api do 
    namespace :fb do 
    post :login 
    resources :my_lists do 
     resources :my_wishes 
    end 
    end 
end 

在我fb_controller我想包括的模塊,這將使我的路徑是這樣的:

/api/fb/my_lists 

這是我的一些fb_controller:

class Api::FbController < ApplicationController 
    skip_before_filter :authenticate_user!, :only => [:login] 

    include MyLists # <-- This is where i want to include the /my_lists 
        # namespace(currently not working, and gives me error 
        # mentioned above) 

    def login 
    #loads of logic 
    end 
end 

MyLists.rb文件(其中我定義了一個模塊)與fb_controller.rb位於同一目錄中。

如何獲取命名空間以指向fb_controller中的模塊,如/ api/fb/my_lists?

回答

6

您已經設置了命名空間正在尋找一個控制器類。如果你想有一個看起來像/api/fb/my_lists的路線,看起來像這樣

class Api::Fb::MyListsController

,但要仍然使用FbController代替有你需要設置你的路線,看起來像這樣

namespace :api do 
    scope "/fb" do 
    resources :my_lists, :controller => 'fb' 
    end 
end 

在我看來,而不包括模塊一個MyListsController 210在你的FbController似乎有點尷尬。

我可能會做的是有一個模塊FB與通用FbController然後有MyListsController < FbController。無論如何,這超出了你的問題的範圍。

上述內容應回答您的需求。

編輯

從您的意見,並在你試圖這樣做什麼我的假設是一個小例子:

的config/routes.rb中

namespace :api do 
    scope "/fb" do 
    post "login" => "fb#login" 
    # some fb controller specific routes 
    resources :my_lists 
    end 
end 

api/fb/fb_controller.rb

class Api::FbController < ApiController 
    # some facebook specific logic like authorization and such. 
    def login 
    end 
end 

API/FB/my_lists_controller.rb

class Api::MyListsController < Api::FbController 
    def create 
    # Here the controller should gather the parameters and call the model's create 
    end 
end 

現在,如果你想創建一個MyList對象,那麼你可以只直接做的邏輯模型。另一方面,如果您想要處理更多的邏輯,您希望將該邏輯放入服務對象中,該服務對象處理創建MyList及其關聯的願望或您的模型。我可能會去服務對象。請注意,服務對象應該是一個類而不是一個模塊。

+0

謝謝!如果我喜歡你的建議,將路線指向我的模塊包含在FbController中?我想要的基本上只是一個主要模塊,並以匹配路線的方式嵌套「子模塊」。 fb控制器允許您編輯/創建包含許多願望的列表。所以我希望list_controller是fb_controller的子模塊,wish_controller是列表控制器的子模塊。那有意義嗎? – 2013-03-20 19:32:53

+0

我認爲你有控制器和模塊混淆。我會以我如何處理你想要做的事情的例子來更新我的答案。 – 2013-03-20 19:44:38

+0

那太棒了,謝謝Leo! – 2013-03-20 19:52:09

1

在你的例子中,Fb不是一個命名空間,它是一個控制器。命名空間調用迫使您的應用程序查找不存在的Fb模塊。嘗試建立這樣的路線:

namespace :api do 
    resource :fb do 
    post :login 
    resources :my_lists do 
     resources :my_wishes 
    end 
    end 
end 

您也可以定義爲API命名空間的新的基本控制器:

# app/controllers/api/base_controller.rb 
class Api::BaseController < ApplicationController 
end 

如果你這樣做,你的其他控制器可以從這個繼承:

# app/controllers/api/fb_controller.rb 
class Api::FbController < Api::BaseController 
end 

正在運行rake routes應該讓你知道你的其他控制器是如何佈局的。只是一個警告 - 通常不建議將資源嵌套超過1深度(您將最終得到像edit_api_fb_my_list_my_wish_path這樣的複雜路徑)。如果你能以一種更簡單的方式來構建它,那麼你可能會有更簡單的時間。

+0

謝謝!如果我按照你的建議,我應該如何添加我的my_lists_controller /模塊?我應該像這樣添加它:class Api :: FbController :: MyWishes ?,或者我可以在FbController中包含一個名爲MyWishes的模塊嗎? – 2013-03-20 19:28:22

相關問題