在Rails路由中进行通配时,约束是否有效?

时间:2014-03-21 13:54:49

标签: ruby-on-rails routing

我有一个网站过去常常在网址上加载大量博客文章:

/blog/2014/03/21/post-name
/2014/03/20/another-post

他们现在已转移到新域名,我正在尝试在路由文件中设置重定向:

match '*path' => 
  redirect{ |params, request|
    "http://ournewdomain.com/#{params[:path]}"
  }, constraints: { :path => %r{(blog/)?\d\d\d\d/\d\d/\d\d/[\w\-_]+} }

但是这会将所有请求重定向到新域 - 就像constraints无效一样。我看过this但看起来这个问题已经解决了? constraints是否适用于globbed路由?

2 个答案:

答案 0 :(得分:0)

我对此稍作调整,似乎有效:

  get '*path', to: redirect {|params, req| 
     "http://ournewdomain.com/#{params[:path]}" },
     constraints: { :path => %r{(blog/)?\d\d\d\d/\d\d/\d\d/[\w\-_]+} }

答案 1 :(得分:0)

如果无法使globbed路径上的constraints正常工作,我目前最终会这样做,这似乎很笨拙,但有效:

match '/:year/:month/:day/:slug',
  to: redirect{ |p, request|
    "http://ournewdomain.com/#{p[:year]}/#{p[:month]}/#{p[:day]}/#{p[:slug]}/"
  }, constraints: {
        :year => /\d\d\d\d/,
        :month => /\d\d/,
        :day => /\d\d/,
        :slug => /[\w\-_]+/ }

# Same as above but with /blog/ prefix.
match '/blog/:year/:month/:day/:slug',
  to: redirect{ |p, request|
    "http://ournewdomain.com/#{p[:year]}/#{p[:month]}/#{p[:day]}/#{p[:slug]}/"
  }, constraints: {
        :year => /\d\d\d\d/,
        :month => /\d\d/,
        :day => /\d\d/,
        :slug => /[\w\-_]+/ }