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.

306 CHAPTER 11 Tagging<br />

The :from option tells Searcher what association this label should be searched upon,<br />

and the :field option tells it what field to perform a lookup on.<br />

The label method is evaluated internally to Searcher and will result in a by_tag<br />

method being defined on your Ticket model, which will be used by the search<br />

method if you pass in a query such as tag:iteration_1. This method will perform an<br />

SQL join on your tags table, returning only the tickets that are related to a tag with the<br />

given name.<br />

With this configuration now in your model, you can define the search action<br />

directly underneath the destroy action in TicketsController to use the search<br />

method on Ticket:<br />

def search<br />

@tickets = @project.tickets.search(params[:search])<br />

end<br />

Assign all the tickets retrieved with the search method to the @tickets variable, which<br />

you would render in the search template if you didn’t already have a template that was<br />

useful for rendering lists of tickets. That template would be the one at app/views/<br />

projects/show.html.erb, but to render it you’re going to make one small modification.<br />

Currently this template renders all the tickets by using this line to start:<br />

<br />

This line will iterate through the tickets in the project and do whatever is inside the<br />

block for each of those tickets. If you were to render this template right now with the<br />

search action, it would still return all tickets. You can get around this by changing the<br />

line in the template to read<br />

<br />

With this change, you break the ProjectsController’s show action, because the<br />

@tickets variable is not defined there. You can see the error you would get when you<br />

run bin/cucumber features/viewing_tickets.feature:<br />

You have a nil object when you didn't expect it!<br />

You might have expected an instance of Array.<br />

The error occurred while evaluating nil.each<br />

To fix this error, you set up the @tickets variable inside the show action of Projects-<br />

Controller, which you should place directly under the definition for the index<br />

action:<br />

def show<br />

@tickets = @project.tickets<br />

end<br />

When you re-run bin/cucumber features/viewing_tickets.feature, you see that it<br />

now passes once again:<br />

1 scenario (1 passed)<br />

23 steps (23 passed)

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

Saved successfully!

Ooh no, something went wrong!