Rails 使用 routes.rb 重定向旧 URL

jyo*_*eph 6 url routes ruby-on-rails

我有一个用 Coldfusion 构建的旧站点,一个用 Rails 构建的新站点。我想将旧 URL 重定向到新 URL。我不确定路线是否适合(我是菜鸟)。URL 将非常相似。这应该很容易,但我不确定最好的方法。

旧网址:

mysite.com/this-is-the-slug-right-here/
Run Code Online (Sandbox Code Playgroud)

新网址:

mysite.com/blog/this-is-the-slug-right-here
Run Code Online (Sandbox Code Playgroud)

这是问题,我有 3 个“内容类型”。旧站点 url 没有区分内容类型。新的 Rails 站点对每种内容类型都有一个控制器:博客、照片、移动照片。

所以在上面的例子中/blog/是控制器(内容类型),this-is-the-slug-right-here是内容的永久链接或 slug。我得到这样的:

@content = Content.where(:permalink => params[:id]).first
Run Code Online (Sandbox Code Playgroud)

我应该使用routes.rb,还是需要某种包罗万象的脚本?任何让我指向正确方向的帮助将不胜感激。


编辑以进一步澄清

这是一篇博文:http : //jyoseph.com/treadmill-desk-walk-this-way/

这个的新 URL 是/blog/treadmill-desk-walk-this-way因为它是博客的内容类型。

还有一张照片:http : //jyoseph.com/berries/

这个的新 URL 是/photos/berries因为它是照片的内容类型。

内容类型是内容模型上的一个属性,存储在属性中content_type


这是我的 routes.rb 文件:

resources :contents
match 'mophoblog/:id', :to => 'mophoblog#show'
match 'photos/:id', :to => 'photos#show'
match 'blog/:id', :to => 'blog#show'

root :to => "index#index"   
match ':controller(/:action(/:id(.:format)))'
Run Code Online (Sandbox Code Playgroud)

使用@mark 的答案得到了它,这就是我的结果。

在我的routes.rb

match ':id' => 'contents#redirect',  :via => :get, :as => :id
Run Code Online (Sandbox Code Playgroud)

在我的内容控制器中:

def redirect
  @content = Content.where(:permalink => params[:id]).first
  if @content.content_type.eql?('Photo')
    redirect_to "/photos/#{@content.permalink}", :status => :moved_permanently   
  elsif @content.content_type.eql?('Blog')
    redirect_to "/blog/#{@content.permalink}", :status => :moved_permanently   
  elsif @content.content_type.eql?('MoPhoBlog')   
    redirect_to "/mophoblog/#{@content.permalink}", :status => :moved_permanently   
  end
end 
Run Code Online (Sandbox Code Playgroud)

我确信这可以改进,特别是我重定向的方式,但这完美地解决了我的问题。

mar*_*ark 4

您不能使用routes.rb 来执行此操作,但是设置路由、获取内容类型和重定向非常简单。

就像是:

routes.rb
match.resources :photos
match.resources :mobile_photos
match.resources :blog
#everything_else all resource and named routes before
match ':article_id' => 'articles#redirect',  :via => :get, :as => :article_redirect

#articles_controller.rb
def redirect
  @content = Content.find params[:id]
  if @content.content_type.eql?('photo')
    redirect_to photo_path(@content), :status => :moved_permanently
  elsif @content.content_type.eql?('mobile_photo')
    redirect_to mobile_photo_path(@content), :status => :moved_permanently
  ...
end
Run Code Online (Sandbox Code Playgroud)

现在,当我写这篇文章时,我突然想到,您可能只需要一个控制器来完成这一切?