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.

Subscribing to updates<br />

Listing 12.9 app/helpers/tickets_helper.rb<br />

def toggle_watching_button<br />

text = if @ticket.watchers.include?(current_user)<br />

"Stop watching this ticket"<br />

else<br />

"Watch this ticket"<br />

end<br />

button_to(text, watch_project_ticket_path(@ticket.project, @ticket))<br />

end<br />

On the final line of this method, you use a new method: button_to. This method<br />

works in a similar fashion as link_to does, providing a user with an element to click to<br />

go somewhere. In this case, the element is a button wrapped in a form that points to<br />

the specified action. When the user clicks the button, it submits this form through a<br />

POST request, with the only parameter passed through being params[:commit], which<br />

contains the text of the button.<br />

Inside the button_to, you use a new route helper that you haven’t defined yet.<br />

When you run bin/cucumber features/watching_tickets.feature, it will complain<br />

that this method is undefined when it tries to render the app/views/tickets/<br />

show.html.erb page:<br />

And I follow "Release date"<br />

undefined method `watch_project_ticket_path' for ...<br />

This route helper points to a specific action on a project’s ticket. You can define it in<br />

config/routes.rb inside the resources :tickets block, which itself is nested inside<br />

the resources :projects block, as shown in the following listing.<br />

Listing 12.10 config/routes.rb<br />

resources :projects do<br />

resources :tickets do<br />

collection do<br />

get :search<br />

end<br />

member do<br />

post :watch<br />

end<br />

end<br />

end<br />

B Define member route<br />

The button_to’s purpose is to toggle the watch status of a single ticket, meaning you<br />

want to define a member route B for your ticket resource. You put it inside the tickets<br />

resource, nested under the projects resource, because for your watch action you want<br />

to confirm that the person has permission to view this project. You define the route to<br />

the watch action with post because button_to generates a form by default, and a<br />

form’s HTTP method will default to POST.<br />

331

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

Saved successfully!

Ooh no, something went wrong!