2016-07-27 135 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 –