我对新的 Rails 应用程序有一个有点奇怪的要求。我需要构建一个应用程序,其中所有路由都在多个命名空间中定义(让我解释一下)。我想要一个应用程序,其中学校科目(数学、英语等)是命名空间:
%w[math english].each do |subject|
namespace subject.to_sym do
resources :students
end
end
这很棒并且有效,但它需要我创建一个命名空间StudentsController
对于每个主题,这意味着如果我添加一个新主题,那么我需要创建一个新控制器。
我想要的是创建一个Base::StudentsController
如果,让我们说Math::StudentsController
存在则使用它,如果不存在则可以动态创建该控制器并继承Base::StudentsController
.
这是可能的事吗?如果是这样,那么我将如何实施呢?
通过这样定义的路由:
%w[math english].each do |subject|
scope "/#{subject}" do
begin
"#{subject.camelcase}::StudentsController".constantize
resources :students, controller: "#{subject}::students", only: :index
rescue
resources :students, controller: "base::students", only: :index
end
end
end
rake routes
输出:
students GET /math/students(.:format) base::students#index
GET /english/students(.:format) english::students#index
如果存在 english/students_controller.rb 和 math/students_controller。缺席。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)