Quick and dirty search in Rails
Ever wondered how to quick have a search function in your rails app?
Here is a super quick and maybe a lil dirty way to achieve so.
First step:
The view
<p><%= form_tag("/searches", :method => "get") do %>
<%= text_field_tag :keywords, params[:keywords] %> </p> <p> <%= submit_tag("Search") %> <% end %> </p>
Second step:
search.rb model (app/models)
class Search < ActiveRecord::Base def self.find_results(search) if search Item.find(:all, :conditions => ['name LIKE ?', "%#{search}%"]) else Item.find(:all) end end end
Third step:
searches_controller.rb (app/controllers)
class SearchesController < ApplicationController def index @results = Search.find_results(params[:keywords]) end end
Fourth step:
index.html.erb (app/views/searches)
<% @results.each do |result| %> <p><%= result.name %></p>
Done :)
Just don’t forget to add resources :searches, :controllers => ‘searches’ to your routes.rb!