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.

Deleting projects<br />

default, this prompt is ignored, so you don’t have to tell Capybara to click OK on the<br />

prompt—there is no prompt because Rails has a built-in fallback for users without<br />

JavaScript enabled. If you launch a browser and follow the steps in the feature to get<br />

to this Delete Project link, and then click the link, you see the confirmation prompt.<br />

This prompt is exceptionally helpful for preventing accidental deletions.<br />

When you run the feature again, it complains of a missing destroy action:<br />

And I follow "Delete Project"<br />

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

The final action you need to implement is in your controller, and you’ll put it underneath<br />

the update action. This action is shown in the following listing.<br />

Listing 4.15 app/controllers/projects_controller.rb<br />

def destroy<br />

@project = Project.find(params[:id])<br />

@project.destroy<br />

flash[:notice] = "Project has been deleted."<br />

redirect_to projects_path<br />

end<br />

Here you call the destroy method on the @project object you get back from your<br />

find. No validations are run here, so no conditional setup is needed. Once you call<br />

destroy on that object, the relevant database record is gone for good but the object<br />

still exists. When it’s gone, you set the flash[:notice] and redirect back to the project’s<br />

index page by using the projects_path routing helper.<br />

With this last action in place, your newest feature should pass when you run bin/<br />

cucumber features/deleting_projects.feature:<br />

1 scenario (1 passed)<br />

6 steps (6 passed)<br />

Let’s see if everything else is running with rake cucumber:ok:<br />

6 scenarios (6 passed)<br />

37 steps (37 passed)<br />

Great! Let’s commit that:<br />

git add .<br />

git commit -m "Implemented delete functionality for projects"<br />

git push<br />

Done! Now you have the full support for CRUD operations in your Projects-<br />

Controller. Let’s refine this controller into simpler code before we move on.<br />

4.3.3 Looking for what isn’t there<br />

People sometimes poke around an application looking for things that are no longer<br />

there, or they muck about with the URL. As an example, launch your application’s<br />

server by using rails server and try to navigate to http://localhost:3000/projects/<br />

not-here. You’ll see the exception shown in figure 4.1.<br />

93

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

Saved successfully!

Ooh no, something went wrong!