目次
HTTPリクエストとコントローラのアクションの対応付け (ルーティング) を設定するためには、config/routes.rb を編集します。内容が重複する場合、先に記述されたものが優先されます。
現在のルーティング情報を知るためには、
rake routes
を実行します。
特殊なルーティング設定
トップページ
routes.rb
RoR::Application.routes.draw do
root :to => "main#index"
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
root GET / main#index
カスタム
あるURLを任意のコントローラ、アクションに結びつけることができます。
:via
get, post, put, deleteが指定できます。
routes.rb
RoR::Application.routes.draw do
match "/signup" => "main#signup", :via => %w[get post]
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
signup GET|POST /signup(.:format) main#signup
個別に指定することもできます。
routes.rb
RoR::Application.routes.draw do
# :asを省略すると、ビュー内などでsignup_url変数などが使用できなくなります。
get "/signup" => "main#signup", :as => "signup"
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
signup GET /signup(.:format) main#signup
getでクエリパラメータを設定
routes.rb
RoR::Application.routes.draw do
# :code以下の正規表現指定の部分は省略可能です。
get "/tarball-:code.tar.gz" => "main#tarball", :code => /\d{4}/
end
あるいは
RoR::Application.routes.draw do
# :code以下の正規表現指定の部分は省略可能です。
get "/tarball-:code.tar.gz" => "main#tarball",
:constraint => {:code => /\d{4}/}
:as => 'tarball'
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
GET /tarball-:code.tar.gz(.:format) main#tarball
例えばGETで/tarball-1000.tar.gzにアクセスすると、main#tarballアクションが実行され、コントローラまたはビュー内ではparams[:code]で値1000が取得できます。
resources
resourcesメソッドの引数として例えば:entriesというシンボルを渡すと、
routes.rb
RoR::Application.routes.draw do
resources :entries
end
自動で「/entries => entriesコントローラのindexアクション」という対応付け等が設定されます。
$ rake routes
Prefix Verb URI Pattern Controller#Action
entries GET /entries(.:format) entries#index
POST /entries(.:format) entries#create
new_entry GET /entries/new(.:format) entries#new
edit_entry GET /entries/:id/edit(.:format) entries#edit
entry GET /entries/:id(.:format) entries#show
PATCH /entries/:id(.:format) entries#update
PUT /entries/:id(.:format) entries#update
DELETE /entries/:id(.:format) entries#destroy
resource
resourceメソッド (先程のresourcesと異なり単数形で's'がないことに注意) に例えば
:entryというシンボルを渡すと、
routes.rb
RoR::Application.routes.draw do
resource :entry
end
自動で以下のような対応付けが設定されます。
$ rake routes
Prefix Verb URI Pattern Controller#Action
entry POST /entry(.:format) entries#create
new_entry GET /entry/new(.:format) entries#new
edit_entry GET /entry/edit(.:format) entries#edit
GET /entry(.:format) entries#show
PATCH /entry(.:format) entries#update
PUT /entry(.:format) entries#update
DELETE /entry(.:format) entries#destroy
ビューでリンクを記述するときに便利な機能
routes.rbルーティングを設定すると、コントローラやビューなどで、
rake routesで表示されるPrefixに_pathまたは_urlをつけた変数から
パスやURL情報を取得できるようになります。
例えば「resources」の項で示した例では以下のようになります。
性質上IDが必要なものは指定が必須です。
また、getパラメータの情報を記述することもできます。
app/views/entries/index.erb
<%= entries_url %><br />
<%= entries_path %><br />
<%= new_entry_url(:p1 => "v1", :p2 => "v2") %><br />
<%= new_entry_path %><br />
<%= edit_entry_url(123) %><br />
<%= edit_entry_path(123) %><br />
<%= entry_url(123, :p1 => "v1", :p2 => "v2") %><br />
<%= entry_path(123) %><br />
app/controllers/entries_controller.rb
class EntriesController < ApplicationController
def index
end
end
ブラウザ表示例 (http://localhost:3000/entries)
http://localhost:3000/entries
/entries
http://localhost:3000/entries/new?p1=v1&p2=v2
/entries/new
http://localhost:3000/entries/123/edit
/entries/123/edit
http://localhost:3000/entries/123?p1=v1&p2=v2
/entries/123
多階層のresource(s)
resourcesあるいはresourcesメソッドをブロックつきで呼びだしネストさせることで、多階層のID関係が必要なルーティングが設定できます。
routes.rb
RoR::Application.routes.draw do
resources :blogs do
resources :entries
end
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
blog_entries GET /blogs/:blog_id/entries(.:format) entries#index
POST /blogs/:blog_id/entries(.:format) entries#create
new_blog_entry GET /blogs/:blog_id/entries/new(.:format) entries#new
edit_blog_entry GET /blogs/:blog_id/entries/:id/edit(.:format) entries#edit
blog_entry GET /blogs/:blog_id/entries/:id(.:format) entries#show
PATCH /blogs/:blog_id/entries/:id(.:format) entries#update
PUT /blogs/:blog_id/entries/:id(.:format) entries#update
DELETE /blogs/:blog_id/entries/:id(.:format) entries#destroy
blogs GET /blogs(.:format) blogs#index
POST /blogs(.:format) blogs#create
new_blog GET /blogs/new(.:format) blogs#new
edit_blog GET /blogs/:id/edit(.:format) blogs#edit
blog GET /blogs/:id(.:format) blogs#show
PATCH /blogs/:id(.:format) blogs#update
PUT /blogs/:id(.:format) blogs#update
DELETE /blogs/:id(.:format) blogs#destroy
resource(s)の機能を制限する
:onlyあるいは:exceptをresource(s)メソッドに渡すことで、自動設定されるルーティングを制限できます。
:only
routes.rb
RoR::Application.routes.draw do
resources :entries, :only => %w[index show]
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
entries GET /entries(.:format) entries#index
entry GET /entries/:id(.:format) entries#show
:except
routes.rb
RoR::Application.routes.draw do
resources :entries, :except => %w[index show]
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
entries POST /entries(.:format) entries#create
new_entry GET /entries/new(.:format) entries#new
edit_entry GET /entries/:id/edit(.:format) entries#edit
entry PATCH /entries/:id(.:format) entries#update
PUT /entries/:id(.:format) entries#update
DELETE /entries/:id(.:format) entries#destroy
resourcesの生成結果に独自の設定を追加する
:member,:collectionシンボルを下記のように指定することで、resourcesで自動生成される結果に独自のルーティングを追加できます。
routes.rb
RoR::Application.routes.draw do
resources :photos do
get :download, :on => :member
get :popular, :on => :collection
end
end
あるいは
RoR::Application.routes.draw do
resources :photos do
member do
get :download
end
collection do
get :popular
end
end
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
download_photo GET /photos/:id/download(.:format) photos#download
popular_photos GET /photos/popular(.:format) photos#popular
photos GET /photos(.:format) photos#index
POST /photos(.:format) photos#create
new_photo GET /photos/new(.:format) photos#new
edit_photo GET /photos/:id/edit(.:format) photos#edit
photo GET /photos/:id(.:format) photos#show
PATCH /photos/:id(.:format) photos#update
PUT /photos/:id(.:format) photos#update
DELETE /photos/:id(.:format) photos#destroy
名前空間
権限毎に階層を分けたい場合に重宝します。
routes.rb
RoR::Application.routes.draw do
namespace :role1 do
resources :entries
end
end
ルーティング表示例
$ rake routes
Prefix Verb URI Pattern Controller#Action
role1_entries GET /role1/entries(.:format) role1/entries#index
POST /role1/entries(.:format) role1/entries#create
new_role1_entry GET /role1/entries/new(.:format) role1/entries#new
edit_role1_entry GET /role1/entries/:id/edit(.:format) role1/entries#edit
role1_entry GET /role1/entries/:id(.:format) role1/entries#show
PATCH /role1/entries/:id(.:format) role1/entries#update
PUT /role1/entries/:id(.:format) role1/entries#update
DELETE /role1/entries/:id(.:format) role1/entries#destroy
コントローラRole1::EntriesControllerのアクションに結びつけられていることが分かります。
関連記事
- レイアウトおよび部分テンプレートに関するまとめ (Rails4)レイアウトおよび部分テンプレートはどちらもテンプレート (*.html.erb) に共通の要素をまとめておき、任意のテンプレートから利用できるようにしておくための仕組みです。フッターやヘッダーといった大枠はレイアウト、小さなパーツは部分テンプレートというイメージで使い分けましょう。 レイアウトの使用方法 クラス毎に指定する方法と、アクション毎に指定する方法があります。 app/views/layo...
- Ruby コードスニペット (正規表現)sample.rb str = "001: This is a string." var1,var2 = 2,3 # 'EOS'とすると#{}による変数展開がなされない (%03dは展開される) doc = (<<"EOS" % var1) # 括弧は省略可。要は<<"EOS"の次の行からEOSまで。(参: <<-"EOS"とすると前に空白...
- OAuthを用いずにTwitterに自動投稿する (回数制限あり, Selenium with Ruby)Seleniumを用いて、OAuthを用いずにTwitterに自動投稿するRubyスクリプトを記述してみます。連続で複数回実行すると、ボット判定としてキャプチャ認証が発生します。その認証までは通過できませんので悪しからず。また、Twitterの仕様変更次第ではDOMの構造が変化するため、下記サンプルは機能しなくなる恐れが有ります。 twitter_post.rb #!/usr/bin/ruby r...
- Ruby における日本語のエンコーディング日本語を含めて多言語対応する際には、Asciiコード以外の文字コードセットが必要になります。日本語が主となる場合、よく使われる文字セットにはUnicode, Shift_JIS, EUC-JPがあります。このうち Unicode だけは特殊であり、世界中のあらゆる文字を収録しようとしていることから 1 文字を表現するために必要なバイト数が大きくなってしまっています。そのため Unicode のうち...
- Rails3ビューテンプレートの基本的な使用方法 (Ruby)Railsでは、ERB (eRuby (テキストファイルにRubyスクリプトを埋込む書式の仕様) をRubyで実装したもの) を用いてHTML内にRubyスクリプトを埋込むことができます。 <% %> で囲むと出力されません (if-elseなど制御構文を記述します) <%= %> で囲むとエスケープ出力されます <%== %> で囲むとエスケープされずに...