Ruby on Rails: Routes.rb
Routing provides URL rewriting in RoR. It's a way to redirect incoming requests to controllers and actions. Routes are defined in "config/routes.rb".
So lets head there are have a look what we can do!
Setting a homepage
A very popular use of routing is setting a homepage. Before we start the routing itself, we need to delete the default homepage which is stored in "public/index.html".
Once that's deleted we can go to "config/routes.rb"; You will see some code that's auto-generated in here. Basically to start our coding you just need to go down past the resources lines (e.g."resources :posts"); now we can set our homepage.
For the blog we created previously you would use something like this for it to start on the index posts page:
match '/', :to => "posts#index"
This basically sets the "/" (homepage) to the controller of "posts" and inside that, the action of "index".
Other Routing
Other routing is very similar to setting a homepage. Lets say for example I wanted my application to create a new session (where sessions is a controller) when I typed the site name (127.0.0.1:PORTNUMBER while testing using terminal)/login (e.g.127.0.0.1:3000/login); and destroy the session when I did the same but with logout; Then I would use code like this:
match '/login', :to => "sessions#new" match "/logout", :to => "sessions#destroy"
Pretty URLs
You can also use "match" to create nice looking URLs for dynamic pages.
For example in our blog application if we wanted to change it so when a user types the following URL (or is redirected or linked there) "http://127.0.0.1:3001/MyPosts/1" it brings them to the post with an id of 1 (with the action of show) - then we would write a line like this:
match "MyPosts/:id", :to => "posts#show"
Its all quite simple code, but it makes a big effect, and making URLs look nice is actually quite a big thing!
Back to Ruby on Rails

