Adding search to a Rails app.

I wanted to add search to my Rails application. Here’s what I did.

1. Search code to the controller, this controller was already built using a scaffold around a Table called “Words”:


  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 }

I added a view based around the index.html.erb already present. It’s basically identical:


Your ads will be inserted here by

Easy AdSense Pro.

Please go to the plugin admin page to paste your ad code.

<h1>Search results</h1>


<% @words.each do |word| %>
    <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>
<% end %>

<br />

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

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

I added the following rule to config/routes.rb:

match ':controller(/:action(/:id))'

Which if I’ve understood it correctly sends any http://blah/anycontroller/action/something to the anycontroller’s action method using something as a parameter (kind of).

I can then do searches such as:



Will need to add a html form to perform the search (somehow).
Clearly not great if you’re code is returning a lot of search results.