View on GitHub

akkunchoi.github.com

Rails3 routes.rb まとめ

はじめに


Rails3


 


The Rails router recognizes URLs and dispatches them to a controllers action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.


: RailsURLURL

Rails2


URL 

 URL URL


URL URL config/routes.rb 

Rails config/routes.rb DSL Rails2Rails3 Rails3 DSL

# config/routes.rb
match "/patients/:id" => "patients#show", :as => :patient

/patients/17  HTTP GET PatientsController  show  id=17 

 (Named Route Helper) 使 URL 
# on view..
patient_path(17) # /patients/17

使URL

 path  url 
# on view..
patient_url(17)  # http://localhost:3000/patients/17


 rake routes 
$ rake routes
patient        /patients/:id(.:format)       patients#show

 rails console  app.patient_path 
$ rails console
[1] (main)> app.patient_path(17)
=> "/patients/17"

Resource Routing


match 使WebCRUDCRUDRails resources 使7(index, new, create, show, edit, update, destroy) 

Rails Resource Routing 使

# config/routes.rb
resources :photos

7
HTTP Verb       Path                    action       named_helper 
---------       -----                   ------       ----------
GET             /photos                 index        photos_path 
GET             /photos/new             new          new_photo_path
POST            /photos                 create       photos_path
GET             /photos/:id             show         photo_path(:id)
GET             /photos/:id/edit        edit         edit_photo_path(:id)
PUT             /photos/:id             update       photo_path(:id)
DELETE          /photos/:id             destroy      photo_path(:id)

PhotosController index, new, create, show, edit, update, destroy 

newcreateeditupdate Rails
index (GET /photos)
  |
  |--> (GET /photos/new)      --> new 
  |                               |
  |                               `-- (POST /photos) --> create
  |
  |-- (GET /photos/:id)      --> show
  |
  |-- (GET /photos/:id/edit) --> edit 
  |                               |
  |                               `--(PUT /photos/:id)--> update
  |
  `-- (DELETE /photos/:id)   --> destroy

# config/routes.rb
# PhotosControllerにひもづける
resources :photos

# 複数のリソースを定義する場合は一行で書いてもOK
resources :photos, :books, :users

id


 show, edit, update, destroy id URL

 resources resource 
# config/routes.rb
resource :profile

:profile  ProfilesController   resources 使

resourcesindex :id 2

6
GET        /profile/new      new       new_profile_path
POST       /profile          create    profile_path
GET        /profile          show      profile_path
GET        /profile/edit     edit      edit_profile_path
PUT        /profile          update    profile_path
DELETE     /profile          destroy   profile_path

Namespace - path and controller prefix


namespace  path  controller 
# config/routes.rb
namespace :admin do
  # コントローラは Admin::PhotosController です
  resources :photos
end

URL Named helper 
# GET        /admin/photos      index   admin_photos_path 
# GET        /admin/photos/new  new     new_admin_photo_path
# 省略...

Scope - controller prefix


Scope 
# config/routes.rb
scope :module => "admin" do
  # コントローラは Admin::PhotosController です
  resources :photos
end

# またはこのようにも記述できます
resources :photos, :module => "admin"

Named helper使
# GET        /photos         index      admin_photos_path 
# GET        /photos/new     new        new_admin_photo_path
# 省略...

Scope - path prefix



# config/routes.rb
scope "/admin" do    
  # コントローラは PhotosController です
  resources :photos
end

# またはこのようにも記述できます
# :path は絶対パスで
resources :photos, :path => '/admin/photos'

Named helperURL使
# GET        /admin/photos          index       photos_path 
# GET        /admin/photos/new      new         new_photo_path
# 省略...

:path 使
# config/routes.rb
# :path は相対パスにする
# /hoge => photo#index に対応
resources :photos, :path => 'hoge' 

Nested Resources - has_many

# config/routes.rb
resources :photos do
  resources :comments
end 

# photo_comments GET /photos/:photo_id/comments     comments#index
# photo_comment  GET /photos/:photo_id/comments/:id comments#show

1Named helper

member, collection - 


7membercollection使 member :id collection:id

GET /photos/:id/preview  preview 
# config/routes.rb
resources :photos do
  member do
    get 'preview'
  end

  # または
  get 'preview', :on => :member
end

GET /photos/search search 
# config/routes.rb
resources :photos do
  collection do
    get 'search'
  end

  # または
  get 'search', :on => :collection
end

collection  match


/photos/hoge, /photos/moge  match 使
# config/routes.rb
resources :photos do
  # TODO Named helperも自動生成できないだろうか...
  # /photos/:action photos#(?-mix:[^0-9]+)
  collection do
    # 数字の場合は member アクションに流れるようにする
    match ':action', :action => /[^0-9]+/
  end
end

Non-Resourceful Routes


resources 

Dynamic



# config/routes.rb
match ':controller(/:action(/:id))'

GET /photos/show/1/2
{ :controller => “photos”, :action => “show”, :id => “1”, :user_id => “2” }


# config/routes.rb
match ':controller/:action/:id/:user_id'

namespace:modulematch:controller使
# config/routes.rb
match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/

Static


URL


# config/routes.rb
match ':controller/:action/:id/with_user/:user_id'

GET /photos/show/1/with_user/2 
{ :controller => “photos”, :action => “show”, :id => “1”, :user_id => “2” }

query strings



# config/routes.rb
match ':controller/:action/:id'

GET /photos/show/1?user_id=2
{ :controller => “photos”, :action => “show”, :id => “1”, :user_id => “2” }

GET /photos/show/1?id=2  :id => '1' :id 

Defaults

# config/routes.rb
# GET /photos/1
# { :controller => "photos", :action => "show", :id => "1", :format => "jpg"
match 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }

Naming - match

# config/routes.rb
# logout_path, logout_url
match 'exit' => 'sessions#destroy', :as => :logout

Constraints (HTTP verb) - HTTP


/photos/showGET
# config/routes.rb
match 'photos/show' => 'photos#show', :via => :get

# 上記と下記は同じ。短縮形
get 'photos/show'


# config/routes.rb
match 'photos/show' => 'photos#show', :via => [:get, :post]

Constraints (parameter) - 


/photos/A12345 /photos/12
# config/routes.rb
match 'photos/:id' => 'photos#show', :constraints => { :id => /[A-Z]\d{5}/ }
# これは同じ意味
match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/ 

^ $ \b \B使使

Constraints (request) - 


ActionDispatch::Request
# config/routes.rb
match "photos", :constraints => {:subdomain => "admin"}

# ブロックを与えることもできる
namespace "admin" do
  constraints :subdomain => "admin" do
    resources :photos
  end
end

Advanced Constraints - 

# config/routes.rb
match "*path" => "blacklist#index", :constraints => BlacklistConstraint.new

class BlacklistConstraint
  def matches?(request)
    # マッチするならtrue 
  end
end

glob

# config/routes.rb
match 'photos/*other' => 'photos#unknown'


# GET /photos/12               :other => "12"
# GET /photos/long/path/to/12, :other => "long/path/to/12".


# config/routes.rb
match 'books/*section/:title' => 'books#show'


# GET /books/some/section/last-words-a-memoir
# {:section => "some/section", :title => "last-words-a-memoir"}

redirection


301 Moved Permanently redirect
# config/routes.rb
match "/stories" => redirect("/posts")

# 値を引き継ぐ場合
match "/stories/:name" => redirect("/posts/%{name}")

# ブロックでもいいよ
match "/stories/:name" => redirect {|params| "/posts/#{params[:name].pluralize}" }
match "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" }

Rack


TODO 
# config/routes.rb
match "/application.js" => Sprockets

 - root

# config/routes.rb
# GET /   => PagesController, 'main' action
root :to => 'pages#main'

Customized Resource


TODO

Resource  Static 

# config/routes.rb
resources :users do
  member do
    match 'category/:category', :action => :show, :as => :category
  end
  resources :images do
    collection do
      match 'category/:category', :action => :index, :as => :category
    end
  end
end
$ rake routes
category_user        /users/:id/category/:category(.:format)             users#show
category_user_images /users/:user_id/images/category/:category(.:format) images#index

/about  /help 

# config/routes.rb
match ':action', :controller => :pages_controller

/about  PagesController#about  /help  PagesController#help 

参考