27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

92 CHAPTER 4 Oh CRUD!<br />

4.3.1 Writing a feature<br />

You’re going to need a feature to get going: a Delete Project link on the show page<br />

that, when clicked, prompts the user for confirmation. You put the feature at features/<br />

deleting_projects.feature using the following listing.<br />

Listing 4.13 features/deleting_projects.feature<br />

Feature: Deleting projects<br />

In order to remove needless projects<br />

As a project manager<br />

I want to make them disappear<br />

Scenario: Deleting a project<br />

Given there is a project called "TextMate 2"<br />

And I am on the homepage<br />

When I follow "TextMate 2"<br />

And I follow "Delete Project"<br />

Then I should see "Project has been deleted."<br />

Then I should not see "TextMate 2"<br />

When you run this feature using bin/cucumber features/deleting_projects<br />

.feature, the first three steps pass, and the fourth fails:<br />

And I follow "Delete Project"<br />

no link with title, id or text 'Delete Project' found ...<br />

4.3.2 Adding a destroy action<br />

Of course, you need to create a Delete Project link for the show action’s template,<br />

app/views/projects/show.html.erb. You put this on the line after the Edit Project link<br />

using the following listing.<br />

Listing 4.14 app/views/projects/show.html.erb<br />

:delete,<br />

:confirm => "Are you sure you want to delete this project?" %><br />

Here you pass two new options to the link_to method, :method and :confirm.<br />

The :method option tells Rails what HTTP method this link should be using, and<br />

here’s where you specify the :delete method. In the previous chapter, the four HTTP<br />

methods were mentioned; the final one is DELETE. When you developed your first<br />

application, chapter 1 explained why you use the DELETE method, but let’s review why.<br />

If all actions are available by GET requests, then anybody can send you a link to, say,<br />

the destroy action for one of your controllers, and if you click that, it’s bye-bye precious<br />

data.<br />

By using DELETE, you protect an important route for your controller by ensuring<br />

that you have to follow the link from the site to make the proper request to delete this<br />

resource.<br />

The :confirm option brings up a prompt, using JavaScript, that asks users if<br />

they’re sure of what they clicked. Because Capybara doesn’t support JavaScript by

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

Saved successfully!

Ooh no, something went wrong!