27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

62 CHAPTER 3 Developing a real Rails application<br />

To review the routes you’ve defined, you can run the rake routes command and<br />

get output similar to the following.<br />

Listing 3.12 rake routes output<br />

root /<br />

{:controller=>"projects", :action=>"index"}<br />

projects GET /projects(.:format)<br />

{:action=>"index", :controller=>"projects"<br />

POST /projects(.:format)<br />

{:action=>"create", :controller=>"projects"}<br />

new_project GET /projects/new(.:format)<br />

{:action=>"new", :controller=>"projects"<br />

edit_project GET /projects/:id/edit(.:format)<br />

{:action=>"edit", :controller=>"projects"}<br />

project GET /projects/:id(.:format)<br />

{:action=>"show", :controller=>"projects"}<br />

PUT /projects/:id(.:format)<br />

{:action=>"update", :controller=>"projects"}<br />

DELETE /projects/:id(.:format)<br />

{:action=>"delete", :controller=>"projects"}<br />

The words in the leftmost column of this output are the beginnings of the method<br />

names you can use in your controllers or views to access them. If you want just the<br />

path to a route, such as /projects, then use projects_path. If you want the full URL,<br />

such as http://yoursite.com/projects, use projects_url. It’s best to use these helpers<br />

rather than hardcoding the URLs; doing so makes your application consistent across<br />

the board. For example, to generate the route to a single project, you would use either<br />

project_path or project_url:<br />

project_path(@project)<br />

This method takes one argument and generates the path according to this object.<br />

You’ll see later how you can alter this path to be more user friendly, generating a URL<br />

such as /projects/1-our-project rather than the impersonal /projects/1.<br />

The four paths mentioned earlier match up to the helpers in table 3.2. Running<br />

rake cucumber:ok now produces a complaint about a missing new action:<br />

When I follow "New Project"<br />

The action 'new' could not be found for ProjectsController<br />

In the following listing, you define the new action in your controller by defining a new<br />

method directly underneath the index method.<br />

URL Helper<br />

GET /projects projects_path<br />

/projects/new new_project_path<br />

/projects/:id project_path<br />

/projects/:id/edit edit_project_path<br />

Table 3.2<br />

RESTful routing matchup

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!