Ruby on the Rails Search Functionality 2nd attempt

My first attempt is here. However that lacked a search box. It was neat in that you could reference the search directly as http://blah/blah/searchstring. However that’s not really what we want, as we want to use search forms and such….

So attempt 2.

First add routes for 2 net methods to routes.rb:

  resources :words do
    collection do
      get 'dosearch'
      get 'search'
    end
  end

I then added 2 new methods to the appropriate controller:

  def search
    @words = Word.where("word = ?",params[:id]) #all #find(params[:id])

    respond_to do |format|
      format.html # search.html.erb
      format.json { render json: @words }
    end
  end

  def dosearch
    @word = ""
    respond_to do |format|
      format.html
      format.json { render json: word }
    end
  end

The first method is as before, and performs the search. The second method really just returns the search html. Perhaps I shouldn’t be using a method for this at all? Just some static html?

Then I added a dosearch.html.erb which will render the search form:

<h1>Search for word</h1>

<%= render 'searchform' %>

<%= link_to 'Back', words_path %>

And a _searchform.html.erb which /actually/ renders the form:

%= form_tag("/words/search", :method => "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:id) %>
  <%= submit_tag("Search") %>
<% end %>

Next I added a search.html.erb for the search results:

<h1>Search Results</h1>

<table>
  <tr>
    <th>Word</th>
    <th>Definition</th>
    <th>Tags</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @words.each do |word| %>
  <tr>
    <td><%= word.word %></td>
    <td><%= word.tags %></td>
    <td><%= word.definition %></td>
    <td><%= link_to 'Show', word %></td>
    <td><%= link_to 'Edit', edit_word_path(word) %></td>
    <td><%= link_to 'Destroy', word, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Word', new_word_path %>

<% if session[:user_id] %>
<%= button_to 'Logout', logout_path, method: :delete %>
<% end %>
</div>
<div id="main" >
<%= yield %>

Which is pretty much a standard index.html.erb to return a list.

That is all.