2013-02-28 66 views
0

我有一個名爲Contributor的模型,它也充當其他幾個模型的名稱空間,例如Contributor::AliasContributor::Reassignment。我想使用包括貢獻者ID像這樣一個URL:Rails 3:獲取名稱空間模型的ID

/contributors/1/reassignments/new 

但我得到這個錯誤:

No route matches [GET] "/contributors/1/reassignments/new" 

routes.rb文件包括:

namespace :contributor do 
    resources :reassignments 
end 
resources :contributors 

我也嘗試過:

resources :contributors do 
    resources :reassignments 
end 

這導致不同的錯誤:

uninitialized constant ReassignmentsController 

任何想法如何處理這個?也許我不應該使用也作爲模型的命名空間?我沒有在任何教程中看到過這一點,儘管看起來這可能是可能的。

UPDATE:

你如何處理深層嵌套的命名空間模型,如:

resources :contributors do 
    resources :reassignments, :module => "contributor" do 
    resources :approvals, :module => "reassignment" 
    end 
end 

使用這種方法,我得到的錯誤:

No route matches {:action=>"create", :controller=>"contributor/reassignment/approvals"} 

我的控制器,目錄不會具有以下結構:

contributor -> 
    reassignment -> 
    approvals_controller.rb 

這似乎與第一個錯誤有關,但也許它是新東西。

回答

1

目前尚不清楚您是否有Contributor資源。如果你這樣做,在你的routes.rb如下:

resources :contributors do 
    resources :reassignments, :module => "contributor" 
end 

如果沒有,請嘗試:

resources :reassignments, :module => "contributor", :path => "/contributors/:contributor_id/reassignments" 

只要注意的是,在第二種情況,你需要構建一個URL,然後明確傳遞:contributor_id在調用link_to,form_for和類似的地方。

如果你想使用[@ contributor,@ reassignment]格式,那麼你最好堅持第一種方法,其中yu有一個Contributor資源。

UPDATE:爲三級嵌套,如果你的控制器的目錄不也是窩在並行,你可以明確指定控制器的資源,例如:

resources :contributors do 
    resources :reassignments, :controller => "contributor/reassignments" do 
    resources :approvals, :controller => "reassignment/approvals" 
    end 
end 

但是,請不要這麼做。在Rails中積極勸阻3層和更多層的嵌套。看看這裏推薦什麼:http://weblog.jamisbuck.org/2007/2/5/nesting-resources

+0

非常好!我對模塊路由不熟悉,但它在這裏做了訣竅。如果你有時間,我有一個相關的問題。我有另一個命名空間/模型嵌套在第二層,我有類似的路由問題。我已經更新了我的問題,如果你有機會,你會看看嗎? – nullnullnull 2013-02-28 03:01:32

+0

您的控制器在approvals_controller.rb中如何定義?是參與者::重新分配:: ApprovalsController還是smth其他?這可能是原因。 – moonfly 2013-02-28 03:23:11

+0

它是'Contributor :: Reassignment :: ApprovalsController'。更新後仍然沒有運氣,但我會繼續嘗試,並讓我知道如果我找到解決方案。如果您有任何其他建議,那也將不勝感激。 – nullnullnull 2013-02-28 03:30:46