search("%#@search%","%#@search%")
end
end
Because you want to use the same view for search, regardless if searching has been done
or not, you just add the @search and @result instance variables if a search has been requested.
Usually you would have checked if the request was a POST or GET to discern if it??™s a search, but
because searches should be idempotent it makes sense to have them be GET too, so you can
give out URLs for a specific search.
CHAPTER 14 ?– THE LIBLIB RAILS APPLICATION 262
The actual searching just uses the LegacySystem module directly, calling the search
method. You add percentage signs before and after the search string to make sure you don??™t try
to match complete strings when searching. Of course, it would be easy to add a small feature
so you can search on either title or author but not both.
The view for the search action should look like Listing 14-3.
Listing 14-3. app/views/book/search.rhtml
Book search
Search for book:
<% form_tag({}, :method => :get) do %>
<%= text_field_tag 'search', @search %>
<%= hidden_field_tag 'searching', 'true' %>
<% end %>
<% if @results %>
<% if @results.empty? %>
No books found
<% else %>
<%= render :partial => 'book_result', :collection => @results %>
<% end %>
<% end %>
<%= link_to 'Add new book',
:action => 'add_description' if @a_librarian %>
First you provide a simple form that also sets the searching parameter to true. You fill in
the text field with the previous search, if one exists.
Pages:
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390