Simple search of entire database?

I am trying to code a simple search, that will search my database for something like what ever the user enters.

I can get the form to render ok, but am having some problems when submitting the test search. I'm wondering if my understanding of this code, which I have put together after reading several different posts on the subject is incorrect.

I have commented what I believe is happenning, so hopefully someone can correct me.

Thanks in advance,

create.rhtml (327 Bytes)

search.rhtml (265 Bytes)

search_controller.rb (346 Bytes)

search.rb (423 Bytes)

better to post the code here

I've got some search code working now that puts the results on the same page. Trouble is the view was generated with scaffolding.

The view contains a table that displays the search results, but it is also displaying all the resources in the DB before a search is run. How can I add something like an if statement to only loop through @resources when a search has been performed? Can I embed it in the view, or should it be in the controller or model?


Code from view:

<h1>Search resources</h1>

<th>Alternative use</th>
<th>resource type</th>

<% @resources.each do |resource| %>

<td><%= resource.subject %></td>
<td><%= resource.course %></td>
<td><%= resource.alternative_use %></td>
<td><%= %></td>
<td><%= resource.subject %></td>
<td><%= link_to 'Show', resource %></td>
<td><%= link_to 'Edit', edit_resource_path(resource) %></td>
<td><%= link_to 'Destroy', resource, :confirm => 'Are you sure?', :method => :delete %></td>
<% end %>

<br />

<%= link_to 'New Resource', new_resource_path %>

<% form_tag resources_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>

I would put this in your controller. And before the search runs, you might want to swap in your search form for the table, so it's perfectly clear what to do.

def search
   if params[:q]
     @resources = [your search logic here]
     render :partial => 'search_form'