2012-05-19 146 views
7

我知道很多rails開發人員說,嵌套你的資源超過2個層次是錯誤的。我也同意,因爲當你的url看起來像mysite.com/account/1/people/1/notes/1時,它會變得混亂。我試圖找到一種方法來使用嵌套的資源,但沒有將它們嵌套3層深。Rails 3級深層嵌套資源

這是做這件事的錯誤方式,因爲rails開發人員不推薦使用它,而且很難弄清楚如何在控制器或窗體視圖中嵌套它。

resources :account do 
    resources :people do 
    resources :notes 
    end 
end 

正確的方法Rails開發者說,這應該做的是,像這樣

resources :account do 
    resources :people 
end 

resources :people do 
    resources :notes 
end 

這裏,我總是碰到的問題。當我訪問帳戶/ 1 /人時,我可以向該帳戶添加一個人,並且可以說該網址就像mysite.com/account/1/people/1,並且工作正常。

現在,如果我嘗試從帳戶1,我得到了錯誤的mysite.com/people/1/notes

找不到人沒有和帳戶ID

哪有讓這個工作正常?

回答

10

你窩深如你喜歡的路線鐵軌3.X讓你展平,然後用淺:真

嘗試用

resources :account, shallow: true do 
    resources :people do 
    resources :notes 
    end 
end 

使用耙路線試驗,看看你會得到什麼: )

更新所評論

正如我所說的,用耙路線玩玩看什麼ü RL的你可以得到

resources :account, shallow: true do 
    resources :people, shallow: true do 
    resources :notes 
    end 
end 

讓你這些路線

:~/Development/rails/routing_test$ rake routes 
     person_notes GET /people/:person_id/notes(.:format)  notes#index 
        POST /people/:person_id/notes(.:format)  notes#create 
    new_person_note GET /people/:person_id/notes/new(.:format) notes#new 
     edit_note GET /notes/:id/edit(.:format)     notes#edit 
       note GET /notes/:id(.:format)      notes#show 
        PUT /notes/:id(.:format)      notes#update 
        DELETE /notes/:id(.:format)      notes#destroy 
    account_people GET /account/:account_id/people(.:format)  people#index 
        POST /account/:account_id/people(.:format)  people#create 
new_account_person GET /account/:account_id/people/new(.:format) people#new 
     edit_person GET /people/:id/edit(.:format)    people#edit 
      person GET /people/:id(.:format)      people#show 
        PUT /people/:id(.:format)      people#update 
        DELETE /people/:id(.:format)      people#destroy 
    account_index GET /account(.:format)      account#index 
        POST /account(.:format)      account#create 
     new_account GET /account/new(.:format)     account#new 
     edit_account GET /account/:id/edit(.:format)    account#edit 
      account GET /account/:id(.:format)     account#show 
        PUT /account/:id(.:format)     account#update 
        DELETE /account/:id(.:format)     account#destroy 

可以看出,你必須在你決定什麼水平,你需要訪問的所有車型。剩下的是放在你的控制器操作中的任何東西。

你真的必須處理這些操作,以確保當id參數沒有被傳入時採取適當的措施,所以如果你使用特定模型的id,檢查id是否在參數列表中,並且如果不採取替代行動。例如如果你不通過帳戶ID然後確保你不嘗試使用它

你的評論指出,你已經使用淺層路線,但這不是你在你的問題中發佈?

+0

我目前在我的路線文件中存在淺層真實,但我不確定如何在沒有帳戶ID的情況下訪問人員/筆記。 Rails拋出這個錯誤'找不到賬號沒有ID' – Yooku

+0

我已經更新了答案。希望澄清事情 – jamesc