如何为多个Rails用户组织类似的路由?

时间:2016-02-03 23:23:01

标签: ruby-on-rails ruby url path routing

假设我有Accountant < User模型和Worker < User模型。他们都需要有“设置”,“仪表板”等页面。

现在路径已分配并在routes.rb中明确定义:

 resources :accountants
 get '/accountant/dashboard' => 'accountant#dashboard'
 get '/accountant/dashboard/:date' => 'accountant#dashboard'
 get '/accountant/settings' => 'accountant#settings'

resources :workers
get '/worker/dashboard' => 'worker#dashboard'
get '/worker/dashboard/:date' => 'worker#dashboard'
get '/worker/settings' => 'worker#settings'

在会话中保存“主页”仪表板路径/作为依赖于当前用户类的应用程序级别帮助程序方法似乎都不是Ruby特色。在Rails 4中有替代方案吗?

1 个答案:

答案 0 :(得分:1)

对于这种情况更好的方法是NameSpace,Rails为我们提供了一个叫做命名空间的东西,你可以在路由中使用它来为你的情况生成不同视图的不同路径可能是这样的:

namespace :accountants do
  get 'dashboard'
  get 'dashboard/:date'
  get 'settings'
end

namespace :workers do
  get 'dashboard'
  get 'dashboard/:date'
  get 'settings'
end

这将生成类似的路线:

localhost:3000/accountants/1/dashboard

localhost:3000/workers/1/settings

这只是一个例子,你总是可以阅读关于它的official documentation,但这是组织你的不同路线思考可扩展性的好方法。

另一种选择是使用角色来管理你拥有的不同用户,因为你的用户模型的扩展随时间不可扩展,将来会有点混乱阅读此代码

问候!

相关问题