# method in block
namespace
# verb options
to: <String || Function> # controller#action, redirect
controllers: <String>
as: <String> # prefix
path: <String> # uri
on: <Symbol> # :collection | :member
path_names: <Hash>
# special verb
resources <:table_names>, <:table_names>
resource <:table_name>, <:table_name>
root: <String> # controller#action
# resource options
shallow: <Boolean>
param: <Symbol>
only: [:action, :action]
except: [:action, :action]
routes 的檔案位置在 config/routes.rb
。
顯示路由
透過網址:http://localhost:3000/rails/info/routes
,或在終端機輸入:
bin/rails routes # 列出所有路由
bin/rails routes -g admin # 搜尋特定路由 (grep)
bin/rails routes -c admin/users # 搜尋路由中特定 controller
目錄
[TOC]
路由設定
基本設定
<verb> <resources>, <options>
Rails.application.routes.draw do
# <verb> <resources> <to: controller#action, as: prefix, path: uri>
get '/posts', to: 'posts#index' # 當網址傳到 /posts 時,使用 PostsController 裡面的 index action
get '/profile', to: :show, controller: 'users'
get '/posts/:id/edit', to: 'pages#edit', as: 'edit_page' # :id 到 C 後會變成 params[:id],把這個路徑設定成 Prefix
get '/members', to: 'posts#edit', path: '/admin/edit_members/members_is' # 透過 path 可以改變 URI,一般是搭配 resources 使用
end
如此我們會得到以下路由:
# 若輸入 /admin/edit_members/members_is 會被帶到 posts#edit ,而原本的 /members 則沒有作用了。
Prefix Verb URI Pattern Controller#Action
posts GET /posts(.:format) posts#index
edit_page GET /posts/:id/edit(.:format) pages#edit
members GET /admin/edit_members/members_is(.:format) posts#edit
resources
url_path
(String)
options
to
: 此路由要對應到哪個controller#action
或redirect
(Function)as
: 改變 rails helper 中使用的 prefix,例如foo_path
,foo_url
path
: 瀏覽器上顯示的 url(顯式出來的網址)
# redirect 使用
get '/stories', to: redirect('/articles') # 直接代入 url
get '/stories/:name', to: redirect('/articles/%{name}') # url 中可代入參數
get '/stories/:name', to: redirect('/articles/%{name}', status: 302) # 可以代入 status code
params
在路由中使用 /:params_name/
時,可以在 controller 的 params
取得 hash { id: '17' }
。
get "/posts/:id/edit", to: "pages#edit", as: "edit_page" # :id 到 Controller 後會變成 params[:id],把這個路徑設定成 Prefix