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.

90 CHAPTER 4 Oh CRUD!<br />

4.2.2 The update action<br />

As the following listing shows, you can now define this update action underneath the<br />

edit action in your controller.<br />

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

def update<br />

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

@project.update_attributes(params[:project])<br />

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

redirect_to @project<br />

end<br />

Notice the new method here, update_attributes. It takes a hash of attributes identical<br />

to the ones passed to new or create, updates those specified attributes on the<br />

object, and then saves them to the database if they are valid. This method, like save,<br />

returns true if the update is valid or false if it is not.<br />

Now that you’ve implemented the update action, let’s see how the feature is going<br />

by running bin/cucumber features/editing_projects.feature:<br />

1 scenario (1 passed)<br />

8 steps (8 passed)<br />

What happens if somebody fills in the name field with a blank value? The user receives<br />

an error, just as in the create action. You should move the first four steps from the<br />

first scenario in features/editing_projects.feature into a Background so the Feature<br />

now looks like the following listing.<br />

Listing 4.10 features/editing_projects.feature<br />

Feature: Editing Projects<br />

In order to update project information<br />

As a user<br />

I want to be able to do that through an interface<br />

Background:<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 "Edit Project"<br />

Scenario: Updating a project<br />

And I fill in "Name" with "TextMate 2 beta"<br />

And I press "Update Project"<br />

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

Then I should be on the project page for "TextMate 2 beta"<br />

Now you can add a new scenario, shown in the following listing, to test that the user is<br />

shown an error message for when the validations fail on update directly under the<br />

other scenario in this file.

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

Saved successfully!

Ooh no, something went wrong!