2016-07-27 133 views
0

我實際上很難找到這個文檔,所以如果你有一個方便的鏈接,這將非常感激。嵌套資源的命名路線

所以我必須:

resources :users do 
    resources :posts, only: [:index, :create, :show] 
    end 

我想通過一個名爲路徑訪問的posts index動作。我試過這個:<%= link_to 'User Posts', user_posts_path %>,但它說它錯過了user_id。有任何想法嗎?

+0

它遺漏'user_id'。如果你想使用嵌套資源,你必須提供一個,否則它沒有任何意義。 –

+0

訪問[this](http://guides.rubyonrails.org/routing.html) –

回答

2

當使用嵌套資源的路線,你需要提供的參考編號父資源。在你的案例資源user。你可以這樣做:user_posts_path(user)。生成的路線是這樣的:/users/1/posts其中1是:user_id或者如果你寧願要像一個路線:/users/posts你應該做的:

resources :users do 
    collection do 
    resources :posts 
    end 
end 

查找有routing documentation here

+0

這是我正在尋找。謝謝 –

0

它要求user_id因爲你定義:用戶的資源,將其更改爲命名空間來代替:

namespace :users do 
    resources :posts, only: [:index, :create, :show] 
end 
+1

請注意,更改爲命名空間將假設您在用戶模塊下嵌套posts_controller,如下所示:'Users :: PostController' – oreoluwa

+0

沒錯,我忘了提及...也許你可以改變你的帖子資源到'user_posts'並避免命名空間。 thx @oreoluwa –