我实际上很难找到这个文档,所以如果你有一个方便的链接,这将非常感激。嵌套资源的命名路线
所以我必须:
resources :users do
resources :posts, only: [:index, :create, :show]
end
我想通过一个名为路径访问的posts
index动作。我试过这个:<%= link_to 'User Posts', user_posts_path %>
,但它说它错过了user_id
。有任何想法吗?
我实际上很难找到这个文档,所以如果你有一个方便的链接,这将非常感激。嵌套资源的命名路线
所以我必须:
resources :users do
resources :posts, only: [:index, :create, :show]
end
我想通过一个名为路径访问的posts
index动作。我试过这个:<%= link_to 'User Posts', user_posts_path %>
,但它说它错过了user_id
。有任何想法吗?
当使用嵌套资源的路线,你需要提供的参考编号父资源。在你的案例资源user
。你可以这样做:user_posts_path(user)
。生成的路线是这样的:/users/1/posts
其中1是:user_id
或者如果你宁愿要像一个路线:/users/posts
你应该做的:
resources :users do
collection do
resources :posts
end
end
这是我正在寻找。谢谢 –
它要求user_id
因为你定义:用户的资源,将其更改为命名空间来代替:
namespace :users do
resources :posts, only: [:index, :create, :show]
end
请注意,更改为命名空间将假设您在用户模块下嵌套posts_controller,如下所示:'Users :: PostController' – oreoluwa
没错,我忘了提及...也许你可以改变你的帖子资源到'user_posts'并避免命名空间。 thx @oreoluwa –
它遗漏'user_id'。如果你想使用嵌套资源,你必须提供一个,否则它没有任何意义。 –
访问[this](http://guides.rubyonrails.org/routing.html) –