Note: This post is intended as a supplement to WTF Just Happened? A Quick Tour of Your First Rails App.
The purpose of the
routes.rb file is to control the conversion from an HTTP request to a Rails method call. You can think of it as a directory that takes a HTTP request and looks up the corresponding Rails controller method.
The REST routes know the action to call in the controller based in the HTTP method. As we have discussed in an earlier article REST and Rails, you will know that a resource comes with seven standard methods for requesting data:
When you add
resources :posts to your
routes.rb file, Rails will generate routes for all seven of these methods. You can, of course, restrict them by using the keyword
only, as in
resources :comments, only: [:create]. This will create a route for creating a comment only.
Each controller action also has a path method as well as a URL method. These can be used in the view template to create a link. Below are the routes for the Posts controller:
You can use routes to reflect a relationship between resources. For example, we have comments belonging to a post so in the
route.rb file, we can write:
resources :posts do resources :comments, only: [:create] end
This is known as a nested route and it means that a comment cannot be viewed outside of the context of a post. See the section ‘Adding comments’ in the Installfest Guide for a worked example.
We are not limited to the routes provided to us by Rails and REST. We can define customised routes to add your own actions to the resource. Each resource call provides three options for specifying custom actions. The
:member option is for actions that apply to a specific resource, the
:collection option is for actions on the entire list (like
index), and the
:new option applies to resources that have not yet been saved to the database.
The one ‘gotcha’ is the a custom resource route needs to be specified twice: once in the controller itself, and then again in
For a more in-depth (and more advanced) article on routing see Rails Routing from the Outside In.