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.

332 CHAPTER 12 Sending email<br />

When you run your feature again using bin/cucumber features/watching<br />

_tickets.feature, it will complain now because there is no watch action for your<br />

button to go to:<br />

And I press "Stop watching this ticket"<br />

The action 'watch' could not be found for TicketsController<br />

You’re almost done! Defining this watch action is the last thing you have to do. This<br />

action will add the user who visits it to a specific ticket’s watcher list if they aren’t<br />

already watching it, or remove them if they are. To define this action you open app/<br />

controllers/tickets_controller.rb and use the code found in the following listing.<br />

Listing 12.11 app/controllers/tickets_controller.rb<br />

def watch<br />

if @ticket.watchers.exists?(current_user)<br />

@ticket.watchers -= [current_user]<br />

flash[:notice] = "You are no longer watching this ticket."<br />

else<br />

@ticket.watchers [:show,<br />

:edit,<br />

:update,<br />

:destroy]<br />

to these lines:<br />

before_filter :find_ticket,<br />

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

:edit,<br />

:update,<br />

:destroy,<br />

:watch]<br />

In this method you use exists?, which will check if the given user is in the list of watchers.<br />

If they are, then you use watchers -= to remove a watcher from a ticket. If they<br />

aren’t on the watchers list, you use watchers

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

Saved successfully!

Ooh no, something went wrong!