Shiva Kumar 's Blog

Start small,Think Big

Rails Routes Part 1 explained ..

Rails routes ,in simple word it connect incoming request from the browser to controller to perform particular action  .Routes file is in your app/config/routes.rb

When a rails application get Url request like this

get /user/17

match “users/:id” => “users#show”

which means it ask the router to look for users controller and show action where user :id => 17

Default Resource Route

Browser request pages from rails by making a request for a URL using specific HHTP method.There are 4 HTTP methods

  1. GET  - It takes request and displays the page
  2. POST- It basically used for creating a form.
  3. DELETE – For deleting a resource
  4. PUT – Its same as the post

Resources creates a CRUD (Create,Read,Update,Delete) and provide mapping between URL and controller .For example a single resources in route file

resources :users

This creates 7 different routes in your application by rails by default to make life easy.

 URL                  HTTP       PATH                              Action                            Used 

users          GET       /users(.:format)                {:action=>”index”,}   show all users
                    POST     /users(.:format)                 {:action=>”create”}  create new user
new_user   GET       /users/new(.:format)           {:action=>”new”} returns a form for creating a new user
edit_user    GET      /users/:id/edit(.:format)       {:action=>”edit”}  return form for editing user
user            GET       /users/:id(.:format)              {:action=>”show”} show specific user
                    PUT        /users/:id(.:format)               {:action=>”update”}  updates specific users
                  DELETE   /users/:id(.:format)               {:action=>”destroy”,} delete specific users

Route to root:

root :to => ‘posts#index’ (This assign the homepage of your app)

This should be on the top of the route file(Order of routes in route.rb is important).

URL and PATHS

Paths

Example :

[gist]2940239[/gist]

whenever you mention helper_method ends with _path ,here it returns ‘/users’ .That is user controller index action displaying all the users

URL

Example :

[gist]2940260[/gist]

There  helper method ends with _url , here it returns the full url something like this http://localhost:3000/users

Since the post is getting long ,the rest of the routes function will be explained in the second part .

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">