[Rails] 2系と3系のルーティング(Routing)の違い

Fri, November 4, 2011 - 3 min read

Ruby on Railsの 2系と3系のRoutingの違いを調べたのでメモ。

Simple routes

# Rails 2:
map.connect 'hello_world', :controller => 'posts', :action => 'index'

# Rails 3:
match 'hello_world' => 'posts#index'

Resources

# Rails 2:
map.resources :users

# Rails 3:
resources :users
# Rails 2
map.resources :games, :member => { :download => :get }, :collection => { :favourites => :get }

# Rails 3
resources :games do
  get :download,   :on => :member
  get :favourites, :on => :collection
end
# Rails 3
resources :games do
  member do
    get :download
  end

  collection do
    get :favourites
  end
end

Root mappings

# Rails 2
map.root :controller => 'posts', :action => 'index'

# Rails 3
root :to => 'posts#index'
# Rails 2
map.namespace :admin do |admin|
  admin.root :controller => 'posts'
end

# Rails 3
namespace :admin do
  root :to => "admin/posts#index"
end

Optional params

# Rails 2
map.connect 'posts/:year/:month', :controller => 'posts',
            :month => nil, :requirements => { :year => /\\d{4}/ }

# Rails 3
match 'posts/:year(/:month)' => 'posts#index', :constraints => { :year => /\\d{4}/ }

【参考】

Rails 3: Routing Examples - Mark Connell はてなブックマーク - Rails 3: Routing Examples - Mark Connell

2.0のmap.resourcesのオプション設定いろいろ - ザリガニが見ていた…。 はてなブックマーク - 2.0のmap.resourcesのオプション設定いろいろ - ザリガニが見ていた...。

map.resourcesを試してみる はてなブックマーク - map.resourcesを試してみる