Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Ruby on Rails: AJAX Live Search using MySQL and Rails

source: http://weknowsnow.com/blog/techside.php?itemid=64

The following code will create a live search in your Ruby on Rails project using AJAX. This Web 2.0 stuff is neaaaato. Yes, I'm sure there are better ways to do this, post a comment if you have them. This works for me right now so I'm going with it. You'll have to reformat the code because I dont have time to do that under this Nucleus blog software. Enjoy and please leave a comment if you find this code helpful! Ruby on Rails makes writing code fun....

Tags: Web 2.0, AJAX, Ruby, Rails, Ruby on Rails, Javascript, Live, Search, Live Search

VIEWS -> yourcontroller -> search.rhtml
   1  
   2  <%= start_form_tag({:action=> "search"}, { :onSubmit => "Element.show('spinner');" }) %>
   3  <table>
   4  <tr>
   5  <td><label for="searchtext"><font size="1"><b>Live TR Search:</b></font></label></td>
   6  <td><%= text_field_tag :searchtext %></td>
   7  <td><img alt="spinner" id="spinner" src="http://dev.backcountrymaps.com/images/spinner.gif" style="display:none;" /></td>
   8  </tr>
   9  </table>
  10  <%= end_form_tag%>
  11  
  12  <%= observe_field(:searchtext,
  13                   :frequency => 0.5,
  14                   :update => :search_hits,
  15                   :loading => "Element.show('spinner')",
  16                   :complete => "Element.hide('spinner')",
  17                   :url => { :action => :live_search }) %>
  18  
  19  <div id="search_hits"></div>

VIEWS -> yourcontroller -> live_search.rhtml
   1  
   2  <% if @results.empty? %>
   3    '<%=h @phrase %>' not found!
   4  <% else %>
   5    '<%=h @phrase %>' found <b><%= @number_match %></b> time(s)!
   6  <% end %>

CONTROLLERS -> yourcontroller.rb
   1  
   2  def live_search
   3  
   4      @phrase = request.raw_post || request.query_string
   5      a1 = "%"
   6      a2 = "%"
   7      @searchphrase = a1 + @phrase + a2
   8      @results = <b>YOURMODEL</b>.find(:all, :conditions => [ "<b>YOURTABLE</b> LIKE ?", @searchphrase])
   9     
  10      @number_match = @results.length
  11     
  12      render(:layout => false)
  13  end


HINT: It would be very easy to step through @results with a for each loop and display any column from the database record using foreach_loopvar.dbcolumn_name.....
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS