2010-09-01 12 views
41

我的很多用戶都繼續使用http://(rails應用程序URL)/博客,但實際上我沒有博客。我終於建立了一個Posterous博客,現在想引導我的用戶在那裏。有沒有辦法使用routes.rb配置它?有沒有更好的方式,不涉及編輯httpd.conf文件?創建到外部URL的導軌路線

回答

57

取決於您使用的Rails版本。

的Rails 3

# in routes.rb 
match "/blog" => redirect("http://example.com/blog"), :as => :blog 

梁2

# in routes.rb 
map.blog '/blog', 
    :controller => "a_helper_controller", 
    :action => "redirect_to_blog" 

# in a_helper_controller.rb 
def redirect_to_blog 
    redirect_to "http://example.com/blog" 
end 
+0

感謝你。關於什麼控制器放置或命名新的幫助控制器的建議? – 2011-03-17 15:44:09

+1

如果你想在你的路線中使用target =「_ blank」怎麼辦? 可以指定這樣的路線: def external_url(); 「http://example.com/blog」;結束 在routes.rb中定義? 我認爲唯一的解決方案是將他們定義爲助手。 – tothemario 2011-10-24 19:25:47

+0

非常感謝! – 2014-04-24 00:59:04

58

我知道這是舊的,所以,如果別人需要這種鋼軌4:

get "/blog" => redirect("http://example.com/blog") 

使用get而不是匹配Rails 4,否則你會得到一個運行時錯誤

+0

這似乎適用於我,但我有一個客戶使用Internet Explorer的問題: 文件關聯 Mime類型:application/json,Windows無法識別此MIME類型。 – user1434177 2014-10-06 02:02:00

+0

對我剛纔的工作非常有幫助。非常感謝你! – kdweber89 2016-05-19 21:41:12

+0

有沒有人知道如何在軌道5中做到這一點?似乎沒有在Rails 4中使用它的方式,但我似乎無法在Rails 5上找到這方面的資源。我一直收到404。 – JohnSalzarulo 2018-02-23 18:40:36