Over a million developers have joined DZone.

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

<%= start_form_tag({:action=> "search"}, { :onSubmit => "Element.show('spinner');" }) %>
<%= text_field_tag :searchtext %>
<%= end_form_tag%> <%= observe_field(:searchtext, :frequency => 0.5, :update => :search_hits, :loading => "Element.show('spinner')", :complete => "Element.hide('spinner')", :url => { :action => :live_search }) %>
VIEWS -> yourcontroller -> live_search.rhtml <% if @results.empty? %> '<%=h @phrase %>' not found! <% else %> '<%=h @phrase %>' found <%= @number_match %> time(s)! <% end %> CONTROLLERS -> yourcontroller.rb def live_search @phrase = request.raw_post || request.query_string a1 = "%" a2 = "%" @searchphrase = a1 + @phrase + a2 @results = YOURMODEL.find(:all, :conditions => [ "YOURTABLE LIKE ?", @searchphrase]) @number_match = @results.length render(:layout => false) 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.....
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}