Simple search of entire database?

Hi,
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,
Jen.

create.rhtml (327 Bytes)

search.rhtml (265 Bytes)

search_controller.rb (346 Bytes)

search.rb (423 Bytes)

better to post the code here

gist.github.com

Hi,
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?

Cheers,
Jen.

Code from view:

<h1>Search resources</h1>

<table>
<tr>
<th>Subject</th>
<th>Course</th>
<th>Alternative use</th>
<th>Author</th>
<th>resource type</th>
<th></th>
</tr>

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

<tr>
<td><%= resource.subject %></td>
<td><%= resource.course %></td>
<td><%= resource.alternative_use %></td>
<td><%= resource.author %></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>
</tr>
<% end %>
</table>

<br />

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

<% form_tag resources_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% 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]
   else
     render :partial => 'search_form'
   end
end

Walter