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.

302 CHAPTER 11 Tagging<br />

get there pretty soon. The second is that there’s no unique identifier for the element<br />

rendered by app/views/tags/_tag.html.erb, which makes removing it from the page<br />

exceptionally difficult with JavaScript. Let’s add a unique identifier now and remove<br />

the element.<br />

11.4.3 Actually removing a tag<br />

You’re removing a tag’s association from a ticket, but you’re not yet showing people<br />

that it has happened on the page. You can fix the second of your aforementioned<br />

problems by changing the span tag at the top of this partial to be this:<br />

<br />

This will give the element a unique identifier, which you can use to locate the element<br />

and then remove it using JavaScript. Currently for the remove action, you’re rendering<br />

nothing. Let’s now remove the render :nothing => true line from this action,<br />

because you’re going to get it to render a template.<br />

If a request is made asynchronously, the format for that request will be js, rather<br />

than the standard html. For views, you’ve always used the html.erb extension, because<br />

HTML is all you’ve been serving. As of now, this changes. You’re going to be rendering<br />

a js.erb template, which will contain JavaScript code to remove your element. Let’s<br />

create the view for the remove action in a file called app/views/tags/remove.js.erb, and<br />

fill it with this content:<br />

$('#tag-').remove();<br />

This code will be run when the request to the remove action is complete. It uses the<br />

jQuery library’s $ function to locate an element with the id attribute of tag-this-tagmust-die<br />

and then calls remove() 3 on it, which will remove this tag from the page.<br />

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

.feature, you see that it now passes:<br />

1 scenario (1 passed)<br />

11 steps (11 passed)<br />

Awesome! With this feature done, users with permission to tag on a project will now<br />

be able to remove tags too. Before you commit this feature, let’s run rake cucumber<br />

:ok spec to make sure everything is ok:<br />

56 scenarios (55 passed)<br />

619 steps (619 passed)<br />

# and<br />

39 examples, 0 failures, 19 pending<br />

That’s awesome too! Commit and push this:<br />

git add .<br />

git commit -m "Added remove tag functionality"<br />

git push<br />

3 http://api.jquery.com/remove/.

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

Saved successfully!

Ooh no, something went wrong!