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”:
controllers/words_controller.rb:
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
I added a view based around the index.html.erb already present. It’s basically identical:
app/views/words/search.html.erb
<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 %>
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:
http://localhost:3000/words/search/wordtosearchfor
Notes
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.
[…] first attempt is here. However that lacked a search box. It was neat in that you could reference the search directly as […]