2011-06-15 204 views
0

在我的應用程序中,我有用戶,然後每個用戶都有一個郵箱,他們在郵件中傳遞消息。我的routes.rb看起來像:Rails 3 - 嵌套資源路由

resources :users do 
    resources :mailboxes 
    end 

如果我做了耙路線,我可以看到這條路對我說:

user_mailbox GET /users/:user_id/mailboxes/:id(.:format)       {:action=>"show", :controller=>"mailboxes"} 

我想在我的應用程序佈局鏈接到這個路徑中,用戶在屏幕頂部找到的一種工具欄。

我的看法代碼:

<%= link_to image_tag("mail_icon.png", :id => 'mail_notice'), user_mailbox_path(current_user)%> 

我遇到的問題是,我得到這個路徑路由錯誤,如果我什麼也不withing用戶/ * - 那麼其他地方在我的應用程序除了資源我的郵箱嵌套在下。如果我在,讓我們說我的用戶的索引頁,路徑確實沒有問題。

No route matches {:action=>"show", :controller=>"mailboxes", 

有沒有什麼我可以錯過這條路線?任何與用戶有關的工作,只是我遇到問題的郵箱。

謝謝

回答

2

這聽起來像郵箱應該是一個單身的資源。

resources :users do 
    resource :mailbox 
end 

否則會認爲用戶有多個郵箱,你必須提供mailbox_iduser_mailbox_path爲好。

user_mailbox_path(current_user, @mailbox) 
+0

Doh,謝謝你的幫助。可能是我在過去幾個月裏第二次或第三次搞砸了。對我感到羞恥。我很感激。 – Kombo 2011-06-15 04:46:33

2

正如你從路線看:

user_mailbox GET /users/:user_id/mailboxes/:id(.:format) 

您需要提供兩個ID的:USER_ID和:郵箱的ID。這是有道理的,如果用戶可以有幾個郵箱。

<%= link_to image_tag("mail_icon.png", :id => 'mail_notice'), 
      user_mailbox_path(current_user, current_user.mailboxes.first) %> 

如果你想用戶只有一個郵箱,然後我會改變這樣的routes.rb中:

resources :users do 
    get :mailbox, :on => :member 
end 

,你會得到這樣的路線:

mailbox_user GET /users/:id/mailbox(.:format) 

這將由mailbox方法處理UsersController,並且您可以通過mailbox_user_path(current_user)在您的視圖中獲取路徑。

+0

謝謝你的幫助喬治。 Bonehead錯誤只是通過用戶。我真的很感謝幫助。我還喜歡使用郵箱作爲一種方法來保持內容的修改。 – Kombo 2011-06-15 04:53:26