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.

96 CHAPTER 4 Oh CRUD!<br />

F<br />

When the test runs, you get a failure:<br />

1) ProjectsController displays an error<br />

message when asked for a missing project<br />

Failure/Error: get :show, :id => "not-here"<br />

Couldn't find Project with ID=not-here<br />

This is the same failure you saw when you tried running the application using rails<br />

server. Now that you have a failing test, you can fix it.<br />

Open the app/controllers/projects_controller.rb file, and put the code from the<br />

following listing underneath the last action in the controller but before the end of the<br />

class.<br />

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

private<br />

def find_project<br />

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

rescue ActiveRecord::RecordNotFound<br />

flash[:alert] = "The project you were looking" +<br />

" for could not be found."<br />

redirect_to projects_path<br />

end<br />

This method has the private method before it, so the controller doesn’t respond to<br />

this method as an action. To call this method before every action, use the<br />

before_filter method. Place these lines directly under the class Projects-<br />

Controller definition:<br />

before_filter :find_project, :only => [:show,<br />

:edit,<br />

:update,<br />

:destroy]<br />

What does all this mean? Let’s start with the before_filter. before_filters are run<br />

before all the actions in your controller unless you specify either the :except or :only<br />

option. Here you have the :only option defining actions you want the before_filter<br />

to run for. The :except option is the opposite of the :only option, specifying the<br />

actions you do not want the before_filter to run for. The before_filter calls the<br />

find_project method before the specified actions, setting up the @project variable<br />

for you. This means you can remove the following line from all four of your actions<br />

(show, edit, update, and destroy):<br />

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

By doing this, you make the show and edit actions empty. If you remove these actions<br />

and run rake cucumber:ok again, all the scenarios still pass. Controller actions don’t<br />

need to exist in the controllers if there are templates corresponding to those actions,<br />

which you have for these actions. For readability’s sake, it’s best to leave these in the

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

Saved successfully!

Ooh no, something went wrong!