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');" }) %> <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>
VIEWS -> yourcontroller -> live_search.rhtml
<% if @results.empty? %> '<%=h @phrase %>' not found! <% else %> '<%=h @phrase %>' found <b><%= @number_match %></b> time(s)! <% end %>
CONTROLLERS -> yourcontroller.rb
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.....
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