Wednesday, November 11, 2009

Ruby on Rails : Simple search engine using Ajax

After type words in the input field and wait awhile, the result will display at the partial page, no need to hit enter.

In views.rhtml
<%= javascript_include_tag "prototype" %>
Search : <%= text_field "article", "title" %>
<%= observe_field :article_title,
:frequency => 1.0,
:update => 'article_list',
:url => { :action => 'search' },
:with => "'search=' + encodeURIComponent(value)"
%>
<div id = 'article_list'>
<%= render :partial => 'article', :collection => @articles %>
</div>

In partial page, _article.rhtml
Title: <%= article.title %><br>
Author: <%= article.author %>
<hr>

In controller.rb
def search
@articles = Article.find(:all,
:conditions => ["lower(title) like ?", "%" + params[:search].downcase + "%"])

if params[:search].to_s.size < 1
@articles = Article.find(:all)
render :partial => 'article', :collection => @articles
else
if @articles.size > 0
render :partial => 'article', :collection => @articles
else
render :text => "Result not found!", :layout => false
end
end
end

** To wider search :
@articles = Article.find(:all, :conditions => ["lower(title) like ? and lower(type) like ?
and number like ?", "%" + params[:search][:title].downcase + "%",
"%" + params[:search][:type].downcase + "%", "%" + params[:search][:number] + "%"])

Prototype Helper : http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001645

2 comments:

  1. do you know how to integrate Sphinx or similar SE with ROR application

    thank you

    ReplyDelete
  2. Check out this, http://programming-tut.blogspot.com/2010/06/ruby-on-rails-full-text-search-options.html

    ReplyDelete