2014-05-07 108 views
4

Ruby on Rails的嵌套的路線,我有兩個型號:與HAS_ONE協會

預訂:

class Reservation < ActiveRecord::Base 
    has_one :car_emission 
end 

CarEmission:

class CarEmission < ActiveRecord::Base 
    belongs_to :reservation 
end 

及以下路線:

resources :reservations do 
    resources :car_emissions 
end 

現在當我想要創建新car_emission我必須訪問的URL是這樣的:

http://localhost:3000/reservations/1/car_emissions/new 

,當我想編輯我的必遊:

http://localhost:3000/reservations/1/car_emissions/1/edit 

反正是有改變路線,我car_emission編輯鏈接看起來就像這樣:

http://localhost:3000/reservations/1/car_emission 

回答

3

你想要做的幾件事情:

1. Create singular resource 
2. Change the `edit` path for your controller 

Singular Resource

至於建議的@sreekanthGS,你會首先最好創建一個單一的資源。這與resources方法的工作方式相同,只不過它將您的路線視爲單個記錄;脫離了index路線等:

#config/routes.rb 
resources :reservations do 
    resource :car_emission # -> localhost:3000/reservations/1/car_emission 
end 

編輯

這將創建一組REST風格的路線,爲您car_emission,但它仍然會帶你到car_emissions#show行動時,你打「裸」鏈接

你會做得最好:

#config/routes.rb 
resources :reservations do 
    resource :car_emission, except: :show, path_names: { edit: "" } 
end 

當您點擊「裸體」鏈接時,這會帶您進入edit動作

1

嘗試:

resources :reservations do 
    resource :car_emissions 
end 

有一種叫做奇異的資源:

http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default

報價:

科:2.5奇異資源

有時候,你有一種資源,客戶總是l無需引用ID即可。例如,您希望/ profile始終顯示當前登錄用戶的配置文件。在這種情況下,你可以使用一個單一的資源映射/配置文件(而不是/資料/:ID)的演出動作:

get 'profile', to: 'users#show' 

傳遞字符串來獲得期望過一個控制器#動作格式,同時通過一個符號將直接映射到一個動作:

get 'profile', to: :show 

這個足智多謀的路線:

resource :geocoder 

創建應用程序中的六個不同的路線,都映射到地理編碼器。

1

shallow: true可能是你想要什麼

resources :reservations, shallow: true do 
    resources :car_emissions 
end 

shallow: true意志窩index:reservationscreatenew行動:car_emissionsupdate動作不會嵌套在裏面。

這會給你看起來像這樣的路線:

GET /reservations/:reservation_id/car_emissions(.:format) caremissions#index 
POST  /reservations/:reservation_id/car_emissions(.:format) caremissions#create 
GET /reservations/:reservation_id/car_emission/new(.:format) caremissions#new 

GET /reservations/:id/edit(.:format) reservations#edit 
PATCH /reservations/:id(.:format)  reservations#update 
PUT /reservations/:id(.:format)  reservations#update 
DELETE /reservations/:id(.:format)  reservations#destroy 
GET /reservations/:id(.:format)  reservations#show 
1

這種類型

http://localhost:3000/reservations/1/car_emission 

的鏈接是給顯示RESTful資源汽車排放,因此使用它進行簡單的編輯,如上面使用的一個可能會與寧靜的資源衝突。

您可以選擇製作一個單獨的Singular資源,並將其指向您所需的路線。