2014-05-16 304 views
1

我正在寻找rake routes与我的嵌套资源的index路径不匹配的原因。嵌套资源的Rails路由索引

这里是我的代码:

namespace :api do 
    resources :photos do 
    resource :comments 
    end 
end 

下面是命令的结果:rake routes | grep comment

  batch_action_admin_user_comments POST  /admin/user_comments/batch_action(.:format)   admin/user_comments#batch_action 
         admin_user_comments GET  /admin/user_comments(.:format)       admin/user_comments#index 
              POST  /admin/user_comments(.:format)       admin/user_comments#create 
        new_admin_user_comment GET  /admin/user_comments/new(.:format)      admin/user_comments#new 
        edit_admin_user_comment GET  /admin/user_comments/:id/edit(.:format)    admin/user_comments#edit 
         admin_user_comment GET  /admin/user_comments/:id(.:format)      admin/user_comments#show 
              PATCH  /admin/user_comments/:id(.:format)      admin/user_comments#update 
              PUT  /admin/user_comments/:id(.:format)      admin/user_comments#update 
              DELETE  /admin/user_comments/:id(.:format)      admin/user_comments#destroy 
          admin_comments GET  /admin/comments(.:format)        admin/comments#index 
              POST  /admin/comments(.:format)        admin/comments#create 
           admin_comment GET  /admin/comments/:id(.:format)       admin/comments#show 
         api_photo_comments POST  /api/photos/:photo_id/comments(.:format)    api/comments#create 
        new_api_photo_comments GET  /api/photos/:photo_id/comments/new(.:format)   api/comments#new 
        edit_api_photo_comments GET  /api/photos/:photo_id/comments/edit(.:format)   api/comments#edit 
              GET  /api/photos/:photo_id/comments(.:format)    api/comments#show 
              PATCH  /api/photos/:photo_id/comments(.:format)    api/comments#update 
              PUT  /api/photos/:photo_id/comments(.:format)    api/comments#update 
              DELETE  /api/photos/:photo_id/comments(.:format)    api/comments#destroy 

我尝试添加only: [:create, :index]comments资源,但只有create路线是可见的。

根据有关nested-resources的文档,我不明白发生了什么。

谢谢你的帮助。

回答

1

这是因为你使用的是singular resourceresource :comments

从文档:

有时候,你有资源的客户端总是仰望没有 引用的ID。例如,您希望/ profile始终显示当前登录用户的配置文件 。在这种情况下,你可以使用 单一资源/配置文件(而不是/profile/:id)映射到 表演动作

你需要使用标准resources方法来得到这个工作(resource省略index行动):

#config/routes.rb 
namespace :api do 
    resources :photos do 
    resources :comments 
    end 
end 
+0

这正是我发布这个答案后几分钟后发现(见下文)。感谢您的快速回复。 – BriceB

+0

Np,希望我的解释能给你一些背景知识,为什么*问题发生了 –

0

我的错误。我的资源中缺少“S”。

namespace :api do 
    resources :photos do 
    resources :comments 
    end 
end 

现在,它的工作。