简体   繁体   English

Rails,将许多命名路由路由到一个操作

[英]Rails, routing many named routes to one action

Is there a simpler way of writing this: 有没有更简单的方式写这个:

  map.old_site_cusom_packages '/customs_packages_options.html', :controller => :public, :action => :redirect_to_home
  map.old_corporate '/corporate.html', :controller => :public, :action => :redirect_to_home
  map.old_track '/track.html', :controller => :public, :action => :redirect_to_home
  map.old_links '/links.html', :controller => :public, :action => :redirect_to_home
  map.old_contact '/contact.html', :controller => :public, :action => :redirect_to_home

I want to send many named routes to one action on one controller, I'm making sure url's left over from an old site redirect to the correct pages. 我想在一个控制器上向一个动作发送许多命名路由,我确保从旧站点遗留的URL重定向到正确的页面。

Cheers. 干杯。

Use the with_options method: 使用with_options方法:

map.with_options :controller => :public, :action => :redirect_to_home do |p|
  p.old_site_custom_packages '/customs_packages_options.html'
  p.old_corporate '/corporate.html'
  p.old_track '/track.html'
  p.old_links '/links.html'
  p.old_contact '/contact.html'
end

You can always write a multi-purpose route with a regular expression to capture the details: 您始终可以使用正则表达式编写多用途路径以捕获详细信息:

old_content_names_regexp = Regexp.new(%w[
  customs_packages_options
  corporate
  track
  links
  contact
].join('|'))

map.old_content '/:page_name.html',
  :controller => :public,
  :action => :redirect_to_home,
  :requirements => {
    :page_name => old_content_names_regexp
  }

That should capture specific pages and redirect them accordingly. 这应该捕获特定页面并相应地重定向它们。 A more robust solution is to have some kind of lookup table in a database that is checked before serving any content or 404-type pages. 更强大的解决方案是在数据库中使用某种查找表,在提供任何内容或404类型页面之前对其进行检查。

Edit : For named routes, it's an easy alteration: 编辑 :对于命名路线,这是一个很容易的改变:

%w[
  customs_packages_options
  corporate
  track
  links
  contact
].each do |old_path|
  map.send(:"old_#{old_path}",
    "/#{old_path}.html",
    :controller => :public,
    :action => :redirect_to_home,
  )
end

In most cases the old routes can be rewritten using the singular legacy route listed first. 在大多数情况下,可以使用首先列出的单一遗留路由来重写旧路由。 It's also best to keep the routing table as trim as possible. 最好保持路由表尽可能的修剪。 The second method is more of a crutch to try and bridge the old routes. 第二种方法更像是试图桥接旧路线的拐杖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM