2010-07-29 188 views
0

我有一個customer模型has_many events當我進入顧客顯示頁面時,我鏈接到customer擁有的所有events。我想添加一個「此客戶的新活動」鏈接。現在,我正在使用<%= link_to "New Event for this Customer", new_event_path %>,但是當我遵循該鏈接時,我必須手動輸入客戶的ID號。我如何自動執行此操作,以便當我單擊「爲此客戶添加新事件」時,rails知道我爲該特定客戶添加了新事件,而不必自己輸入customer_id?添加新孩子時將新孩子與其父母鏈接

回答

3

你在找什麼叫做nested resources,這裏是good introduction

對於這個特定的情況下,你應該聲明你的路由這樣的:

map.resources :customers do |customers| 
    customers.resources :events 
end 

以上聲明將允許你定義喜歡的路線:

new_customer_event_url(@customer.id) 
=> customers/:customer_id/events/new 

並在您的具體情況:

<%= link_to "New Event for this Customer", new_customer_event_path(@customer) %> 
+0

這很好,謝謝。我的下一個問題是一旦我在孩子身邊,我該如何鏈接回其父母展示頁面? – Reti 2010-07-29 20:20:25

+0

假設您在控制器中定義了「@ customer」,您將能夠定義以下鏈接,link_to「Customer」,customer_path(@customer)'。也許'def find_customer; @customer = Customer.find(params [:customer_id]); end;' – jpemberthy 2010-07-29 21:07:45

+0

PD,如果你想查看'customers'的所有生成路由,你總是可以運行'rake routes | grep客戶',這有助於很多。 – jpemberthy 2010-07-29 21:11:24

0

將客戶ID添加到鏈接中作爲參數<%= link_to "New Event for this Customer", new_event_path, {:cust_id => customer.id} %>,並在窗體中將其設置爲事件對象的隱藏參數。您的模型將自動填入客戶ID。