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
Ruby On Rails: AJAX Live Search Using MySQL And Rails
<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
Snippets Manager replied on Wed, 2007/07/11 - 1:14am
Snippets Manager replied on Wed, 2007/07/11 - 11:35am
Snippets Manager replied on Wed, 2007/07/11 - 11:35am