2016-01-13 54 views
0

我碰到我的第一個問題與嵌套的資源,並從文檔正確配置嵌套資源與變淺

http://guides.rubyonrails.org/routing.html#limits-to-nesting

我不完全能夠想出如何使這個意義上說,以及如何將其應用正確我的情況,目前我的東西都設置這樣的:

resources :stores do 
    resources :locations do 
     resources :business_hours 
    end 
    end 

現在我想限制嵌套,他們推薦的方式,但我對如何實現這一目標不確定,因爲地點屬於商店和商店小時屬於地點。

回答

0

rails文檔基本上是說,上面的資源配置會在網頁上看起來像這樣的url。

mywebapplication.com/stores/1/locations/1/business_hours/1

與你的代碼

stores_locations_business_hours_url

相應軌輔助方法,現在確實沒有什麼不對的,你可以這樣來做,但是你會開始尤其是在您的business_hours控制器中遇到單調乏味的問題。原因是因爲對於你的控制器,你將不得不傳入每個@model對象前面的內容。你必須做一些像

stores_locations_business_hours_url([@store,@location,@business_hour])

訪問的頁面。要限制你需要做這樣的事情:

resources :stores do 
    resources :locations, shallow: true 
end 

resources :locations do 
    resources :business_hours 
end 

所以現在不是mywebapplication.com/stores/1/locations/1的URL會喜歡這個mywebapplication.com/locations/1,現在你的營業時間URL將是一個級深。這就是文檔的含義。

0

要轉到什麼Rails的要你做什麼,你所要做的就是添加shallow: true到每個嵌套resources的:

resources :stores do 
    resources :locations, shallow: true do 
    resources :business_hours, shallow: true 
    end 
end 

這會產生,因爲他們所說的那樣,「路線與少量的信息來唯一地標識資源」,這是這樣的:

    Prefix Verb URI Pattern           Controller#Action 
    location_business_hours GET /locations/:location_id/business_hours(.:format)  business_hours#index 
      business_hour GET /business_hours/:id(.:format)      business_hours#show 
      store_locations GET /stores/:store_id/locations(.:format)    locations#index 
        location GET /locations/:id(.:format)        locations#show 
        stores GET /stores(.:format)         stores#index 
        store GET /stores/:id(.:format)        stores#show 

locations收集動作,例如。 index,得到stores下築巢,因爲locations屬於stores,而是確定一個特定的位置,路線引用locations/1沒有stores/前綴,因爲你並不需要一個store ID來標識location

這落下下來的樹:識別business_hours收集動作,你需要的location小時屬於,而是因爲你有一個location ID,你並不需要涉及的store,讓您得到locations/:id/business_hours。當你想要一組特定的小時時,你不需要location了,所以你只需要/business_hours/1

如果要維持的時間收集路徑的整個層次(即/stores/1/location/2/business_hours),你需要或者不shallowlocations路徑,這將保證其成員的行爲(showedit等)/stores/1/locations/2下,或者你需要使用更少的Rails的助手手動指定你想要的路徑。