ruby-on-rails-3 – 嵌套资源子目录中的分组控制器

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 嵌套资源子目录中的分组控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想组织我的控制器在子目录.这是一个例子:

routes.rb中:

resources :locations do
  resources :users
end

我想把我的控制器放在相应的子目录中:

app/controllers/locations/users_controller.rb

并且url将是(标准):

/locations/1/users
/locations/1/users/new
/locations/1/users/10/edit
...

如果我在路由中有一个命名空间,我可以将我的users_controller.rb更改为

class Locations::UsersController < LocationsController
end

但它不适用于嵌套资源,而是会收到以下错误

Routing Error
 uninitialized constant UsersController

更新

如果我补充说:

resources :locations do
  resources :users
end
match 'locations/:location_id/users' => "locations/users#index"

但是我必须为每个动作和嵌套资源添加路由…

解决方法

如果你想使用那条路线:
match 'locations/:location_id/users' => "locations/users#index"

这可能会在可能与该匹配冲突的任何其他资源/匹配之前发生.默认情况下,Rails路由是顶层的.

# should be before locations resource
resources :locations do
  resources :users
end

或者,如果您想将所有嵌套的用户资源转移到位置/用户,您可以将控制器分配给资源.

resources :locations do
  resources :users,:controller => "locations/users"
end
原文链接:https://www.f2er.com/ruby/271921.html

猜你在找的Ruby相关文章