最近我遇到了访问命名空间控制器的问题,我在education/educations_controller.rb
中有一个父控制器
class Education::EducationssController < ApplicationController
def process_educations
if highschool
controller_to_redirect = 'highschool'
if bacholors
controller_to_redirect = 'bacholors'
else
controller_to_redirect = 'masters'
end
redirect_to :controller => controller_to_redirect, :action => 'process_educations'
end
end
三个子控制器education/highschool_controller.rb
,education/bacholors_controller.rb
,education/masters_controller.rb
,educations_controller.rb
中存在的所有参数传递给这些控制器
class Education::HighschoolController < Education::EducationssController
def proceed_educations
do some process
end
end
class Education::BacholorsController < Education::EducationssController
def proceed_educations
do some process
end
end
class Education::MastersController < Education::EducationssController
def proceed_educations
do some process
end
end
之后各个视图都会出现,但是在这个过程中,url变得太长,所以我想从url中删除所有控制器,然后进行处理,无论用户被带到同一个url,为此我改变了{{1作为
routes.rb
这会为每个控制器生成相同的网址,但当我尝试按namespace :educations,:path => '' do
scope "/educations" do
get 'proceed_educations',to:'educations#proceed_educations'
post 'proceed_educations',to:'educations#proceed_educations'
end
resource :highschool ,:path => '' do
get 'proceed_educations',to:'highschool#proceed_educations'
post 'proceed_educations',to:'highschool#proceed_educations'
end
resource :bacholors ,:path => '' do
get 'proceed_educations',to:'bacholors#proceed_educations'
post 'proceed_educations',to:'bacholors#proceed_educations'
end
resource :masters ,:path => '' do
get 'proceed_educations',to:'masters#proceed_educations'
post 'proceed_educations',to:'masters#proceed_educations'
end
end
访问它们时,它们始终会重定向到同一控制器educations_controller.rb
。
我不知道我做错了什么,请帮助我理解这个过程,或者如果还有更好的方法,那么请建议。
答案 0 :(得分:1)
如果您想避免为两个命名空间控制器创建相同的URL,那么rails很难理解哪个控制器要发送哪个请求。
但是,你可以做的是,在你的routes.rb
中,你可以消除显示控制器名称,并可以在那里增加空间以区别对待,如下所示:
namespace :educations,:path => '' do
scope "/educations",:path => '' do
get 'proceed_educations',to:'educations#proceed_educations',:path => ''
post 'proceed_educations',to:'educations#proceed_educations',:path => ''
end
resource :highschool ,:path => '' do
get 'proceed_educations',to:'highschool#proceed_educations'
post 'proceed_educations',to:'highschool#proceed_educations'
end
resource :bacholors ,:path => ' ' do
get 'proceed_educations',to:'bacholors#proceed_educations',:path => ''
post 'proceed_educations',to:'bacholors#proceed_educations',:path => ''
end
resource :masters ,:path => ' ' do
get 'proceed_educations',to:'masters#proceed_educations',:path => ''
post 'proceed_educations',to:'masters#proceed_educations',:path => ''
end
end
这样,URL就会相同,但会有额外的空格。