Rails 4:命名空间下的路由错误

时间:2014-06-13 06:21:00

标签: ruby-on-rails ruby-on-rails-4

在routes.rb中:

namespace :account do
  resource :groups
  resource :posts
end

但是找到http://0.0.0.0:3000/account/groups时出错:

***Unknown action
The action 'show' could not be found for Account::GroupsController***

我检查了http://0.0.0.0:3000/rails/info/routes并得到了:

```
account_groups_path          POST    /account/groups(.:format)   account/groups#create
new_account_groups_path      GET     /account/groups/new(.:format)   account/groups#new
edit_account_groups_path     GET     /account/groups/edit(.:format)  account/groups#edit
                             GET     /account/groups(.:format)   account/groups#show
                             PATCH   /account/groups(.:format)   account/groups#update
                             PUT     /account/groups(.:format)   account/groups#update
                             DELETE  /account/groups(.:format)   account/groups#destroy
```

为什么帐户/群组不会映射到索引方法?

1 个答案:

答案 0 :(得分:1)

如果您只想生成index操作,请更新路径文件,将创建的路线限制为index,如下所示:

namespace :account do
  resource :groups, only: [ :index ]
  resource :posts
end

问题是您的资源声明,您使用 singular resource ,即resource :groupsresource :posts。这样做的是将/account/groups映射到account/groups#showaccount/posts#show。多个resource将是一个更好的解决方案:

namespace :account do
  resources :groups
  resources :posts
end

通过此更改,运行rake routes可为您提供所需的index操作。