DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby On Rails: AJAX Live Search Using MySQL And Rails

03.13.2006
| 63901 views |
  • submit to reddit
        <a href="http://weknowsnow.com/blog/techside.php?itemid=64">source: http://weknowsnow.com/blog/techside.php?itemid=64</a>

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

<b>VIEWS -> yourcontroller -> search.rhtml</b>
<%= start_form_tag({:action=> "search"}, { :onSubmit => "Element.show('spinner');" }) %>
<table>
<tr>
<td><label for="searchtext"><font size="1"><b>Live TR Search:</b></font></label></td>
<td><%= text_field_tag :searchtext %></td>
<td><img alt="spinner" id="spinner" src="http://dev.backcountrymaps.com/images/spinner.gif" style="display:none;" /></td>
</tr>
</table>
<%= end_form_tag%>

<%= observe_field(:searchtext,
                 :frequency => 0.5,
                 :update => :search_hits,
                 :loading => "Element.show('spinner')",
                 :complete => "Element.hide('spinner')",
                 :url => { :action => :live_search }) %>

<div id="search_hits"></div>
<b>VIEWS -> yourcontroller -> live_search.rhtml</b>
<% if @results.empty? %>
  '<%=h @phrase %>' not found!
<% else %>
  '<%=h @phrase %>' found <b><%= @number_match %></b> time(s)!
<% end %>
<b>CONTROLLERS -> yourcontroller.rb</b>
def live_search

    @phrase = request.raw_post || request.query_string
    a1 = "%"
    a2 = "%"
    @searchphrase = a1 + @phrase + a2
    @results = <b>YOURMODEL</b>.find(:all, :conditions => [ "<b>YOURTABLE</b> 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.....    

Comments

Snippets Manager replied on Fri, 2007/11/02 - 6:44am

Dear Friends, I encountered the problem with the "=" symbol in searchstring, I did many trials and found the following : as zzeroo mentioned we need to use the :with parameter but shouldn't use the "=" symbol. my view contains : <%= observe_field(:searchtext, .............. :with => "searching")%> and we can get this searchtext value in the controller as : def live_search @searchstring = params[:searching] .... end And finally the searchstring doesn't contain the "=" symbol.

Snippets Manager replied on Wed, 2007/07/11 - 1:14am

Hi Folks, I run in this problem a few months, too. Please see @ http://wiki.rubyonrails.org/rails/pages/observe_field+-+Passing+Parameters. There is shown the right way to handle params. The trick is the parameter :with => '"querystring="' in your observer_field (note the equal sign beyond querystring). In Your controllers params[:querystring] shows then the right value without the wicked = Sorry about my ugly english.

Snippets Manager replied on Wed, 2007/07/11 - 11:35am

Ok i have the search working but it won't print the correct results. Before i type anything into the search box the screen will be blank as it should. When i begin typing 'Pete' .... a customer name that i know exists in the database table column, i receive the following response: 'Pete=' not found! My first question is, why is there an "=" in the search query? I have checked my code over and over for a wrongly placed one but everything seems correct. When i delete the search from the box, the label displayed is as follows: '' found 2 time(s)! This is correct as there are only two items in this particular table at this time, so i know something is right...i just can't work out whats wrong! I would be very grateful of any help anyone could offer me. Kind Regards

Snippets Manager replied on Wed, 2007/07/11 - 11:35am

Hey, I am trying to implement this...with difficulty. Could you please confirm to me how exactly i would change this line to apply to my application: @results = YOURMODEL.find(:all, :conditions => [ "YOURTABLE LIKE ?", @searchphrase]) For example my MODEL is called: 'customer.rb' & my TABLE (In my database i pressume?!) is called: 'customers' Would this result in the line of code being altered as so... @results = customer.find(:all, :conditions => [ "customers LIKE ?", @searchphrase]) Hope i am not being too stupid here. I am just having issues making this work. Cheers Pete