方法
- R
執行個體公開方法
redirect(*args, &block) 連結
重新導向任何路徑至其他路徑
get "/stories" => redirect("/posts")
將重新導向使用者,同時略過目前要求的特定部分,包括查詢字串等。/stories
、/stories?foo=bar
等路徑皆會重新導向至 /posts
。
重新導向預設會使用 301 永久搬移
狀態碼。這可使用 :status
選項來覆寫。
get "/stories" => redirect("/posts", status: 307)
您也可以在提供的重新導向參數中使用插入。
get 'docs/:article', to: redirect('/wiki/%{article}')
請注意,如果您傳回沒有前導斜線的路徑,則 URL 會加上前導字串,即目前的 SCRIPT_NAME 環境變數。此變數通常為「/」,但在已安裝引擎的情況下或當應用程式部署在網站的子目錄的情況下,可能有所不同。
您也可以使用其他語法
重新導向的區塊版本允許輕鬆封裝與所述重新導向相關的任何邏輯。會提供 params 和 request 作為參數,或僅提供 params,視您的區塊接受多少參數而定。必須傳回字串作為回傳值。
get 'jokes/:number', to: redirect { |params, request|
path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
"http://#{request.host_with_port}/#{path}"
}
請注意重新導向區塊的 do end
語法無法運作,因為 Ruby 會將區塊傳遞給 get
,而非 redirect
。請改用 { ... }
。
重新導向選項版本允許您僅提供需要變更的 URL 部分,它也支援與第一個範例中類似的路徑插入。
get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}')
get '/stories', to: redirect(path: '/posts')
這將重新導向使用者,同時只變更要求中的指定部分,例如最後一個範例中的 path
選項。/stories
、/stories?foo=bar
分別重新導向至 /posts
和 /posts?foo=bar
。
最後,可以提供一個對呼叫有反應的物件來重新導向,讓您可以重新使用常見的重新導向路徑。呼叫方法必須接受兩個參數,params 和 request,並傳回一個字串。
get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
來源:顯示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/routing/redirection.rb, line 204 def redirect(*args, &block) options = args.extract_options! status = options.delete(:status) || 301 path = args.shift return OptionRedirect.new(status, options) if options.any? return PathRedirect.new(status, path) if String === path block = path if path.respond_to? :call raise ArgumentError, "redirection argument not supported" unless block Redirect.new status, block end