Saturday, May 19, 2012

Rails 3 - Routing

Purpose of rails router is that understanding requesting URLs and dispatches them to a controller's action.

Rails 3 introduced new routing DSL which is slight different than rails 2

Examples:

1. Simple route to welcome page which is handled by index action in shops controller

# Rails 2
map.connect 'welcome', :controller => 'shops', :action => 'index'

# Rails 3
match 'welcome' => 'shops#index'

2. Resources - which allows us to quickly declare all of the common routes for a given resourceful controller

# Rails 2

map.resources :products

# Rails 3

resources :products
It creates different routes in your application for Products controller. The routes are /products,/products/new,/products/:id,/products/:id/edit,etc.

3. Namespaces and Routing

Suppose if you want to organize group of controller under a namespace, Example scenario would be mapping admin specific controllers under admin namespace.

# Rails 2

map.namespace :admin do |admin|
  admin.resources :controller => 'orders'
end

# Rails 3
namespace :admin do
  resources :orders
end

In this case you can access admin specific controllers by /admin/orders, etc

4. Simple ROOT mapping on rails 2 and rails 3

# Rails 2

map.root :controller => 'stores', :action => 'index'

# Rails 3

root :to => 'stores#index'

Stores's index action will be called if you access web application directly - http://example.com

No comments:

Post a Comment