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.

esources :tickets do<br />

resources :comments<br />

resources :tags do<br />

member do<br />

delete :remove<br />

end<br />

end<br />

end<br />

Deleting a tag<br />

By nesting the tags resource inside the ticket’s resource, you are given routing helpers<br />

such as ticket_tag_path. With the member block inside the resources :tags, you can<br />

define further actions that this nested resource responds to. You’ll define that you<br />

should accept a DELETE request to a route to a remove action for this resource, which<br />

you should now create.<br />

Before you add this action to the TagsController, you must first generate this controller<br />

by using<br />

rails g controller tags<br />

Now that you have a controller to define your action in, let’s open app/controllers/<br />

tags_controller.rb and define the remove action in it like this:<br />

def remove<br />

@ticket = Ticket.find(params[:ticket_id])<br />

if can?(:tag, @ticket.project) || current_user.admin?<br />

@tag = Tag.find(params[:id])<br />

@ticket.tags -= [@tag]<br />

B Remove tag<br />

@ticket.save<br />

render :nothing => true<br />

end<br />

end<br />

In this action, you find the ticket based on the id passed through as params[:ticket],<br />

and then you do something new. On the left side of -= B you have @ticket.tags. On<br />

the right, is an array containing @tag. This combination will remove the tag from the<br />

ticket, but will not delete it from the database.<br />

On the second-to-last line of this action, you save the ticket minus one tag. On the<br />

final line you tell it to return nothing, which will return a 200 OK status to your<br />

browser, signaling that everything went according to plan.<br />

When you re-run your scenario it will now successfully click the link, but the tag is<br />

still there:<br />

When I follow "delete-this-tag-must-die"<br />

Then I should not see "this-tag-must-die"<br />

Failed assertion, no message given. (MiniTest::Assertion)<br />

Your tag is unassociated from the ticket but not removed from the page, and so your<br />

feature is still failing. The request is made to delete the ticket, but there’s no code currently<br />

that removes the tag from the page. There are two problems you must overcome<br />

to make this work. The first is that there’s no code. That part’s easy, and you’ll<br />

301

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

Saved successfully!

Ooh no, something went wrong!