Skip to content
antislice edited this page Apr 10, 2013 · 3 revisions
  • root :to => 'topics#index' is a rails route that says the default address for your site is topics#index. topics#index is the topics list page (the topics controller with the index action).
  • Rails routes control how URLs (web addresses) get matched with code on the server. Similar to how addresses match with houses and apartments.
  • The file config/routes.rb is like an address directory listing the possible addresses and which code goes with each one
  • routes.rb uses some shortcuts so it doesn't always show all the possible URLs. To explore the URLs in more detail we can use the terminal.

At the terminal type rake routes. You should get something that looks like this:

    $ rake routes

         votes GET    /votes(.:format)           votes#index
               POST   /votes(.:format)           votes#create
      new_vote GET    /votes/new(.:format)       votes#new
     edit_vote GET    /votes/:id/edit(.:format)  votes#edit
          vote GET    /votes/:id(.:format)       votes#show
               PUT    /votes/:id(.:format)       votes#update
               DELETE /votes/:id(.:format)       votes#destroy
        topics GET    /topics(.:format)          topics#index
               POST   /topics(.:format)          topics#create
     new_topic GET    /topics/new(.:format)      topics#new
    edit_topic GET    /topics/:id/edit(.:format) topics#edit
         topic GET    /topics/:id(.:format)      topics#show
               PUT    /topics/:id(.:format)      topics#update
               DELETE /topics/:id(.:format)      topics#destroy
          root        /                          topics#index

This shows all the URLs your application responds to. The code that starts with colons are variables so :id means the id number of the record. The code in parenthesis is optional.

Exploring Routes (optional)

Now you can have a look at the paths that are available in your app. Let's try looking at one of the topics routes we just generated. Open up your rails console and play:

$ rails console
>> app.topics_path
=> "/topics"
>> app.topics_url
=> "http://www.example.com/topics"

app is a special object that represents your entire application. You can ask it about its routes (as we just did), play with its database connections, or make pseudo-web requests against it with get or post (and lots more).

Clone this wiki locally