2013-02-23 77 views
0

我試圖使用Ruby on Rails將新的location添加到restaurant使用new_foo_path添加具有外鍵關係的新記錄(@bar)

restaurants#show行動我跑:

​​

我也得到一個URL:http://localhost:3000/locations/new.1,其中1是餐廳的ID。但是新的位置表單未顯示。

什麼是軌道方式來處理這個簡單的情況?是否正在使用new_FOO_path甚至是正確的事情?

在這種情況下,我不應該有一個下拉選擇餐廳,因爲我希望最終用戶只能夠一個location添加到自己的餐廳。我不知何故需要在添加位置表單中添加帶餐廳ID的隱藏輸入,並且還要驗證後端的ID。

回答

0

我會在您的routes.rb中創建一個nested resource。例如:

resources :restaurants do 
    resources :locations 
end 

然後您的鏈接目標將是new_restaurant_location_path(@restaurant)。在您的控制器中,您可以通過Restaurant.find(params[:restaurant_id])找到餐廳。

或者,將餐廳ID設置爲GET參數new_location_path(:restaurant_id => @restaurant.id)

+0

我似乎無法找到restaurant_id作爲隱藏字段。如何在視圖中訪問它以在POST操作方法中設置正確的'restaurant_id'? – sergserg 2013-02-23 16:13:33

+0

你不需要。使用嵌套路線,restaurant_id是路徑的一部分。例如:'/ restaurants/1/locations/new'。確保您的位置在您的控制器中正確構建,例如'@location = @ restaurant.location.build',那麼表單應該使用正確的路線。或者使用'form_for [@restaurant,@location]'。 – ashtom 2013-02-23 16:19:45

相關問題