Tuesday, August 4, 2009

Implementing "google search" like search field using Searchlogic

I just wanna a single search field like how it is in google.com. This search field should then search through all the desired columns and return records with matches.

# View
<% form_for @search do |f| %>
<%= f.text_field :keyword %>
<%= f.submit 'Search' %>
<% end %>

# Controller
# Using Seachlogic with Will Paginate
class EnrollmentsController < ApplicationController

def index
@search = Enrollment.search(params[:search])
@enrollments, @enrollments_count = @search.paginate(:include => [{:addresses => :address_type}, :course, :gender], :page => params[:page], :per_page => 20), @search.count
end

end

# Model
# params[:search][:keyword] will trigger keyword namedscope
class Enrollment < ActiveRecord::Base

named_scope :keyword, lambda {|keyword|
{ :conditions => [
"first_name like :word or last_name like :word or nric like :word or date_of_birth like :word or mentor like :word or school_approval_status like :word or student_confirmation_status like :word or genders.name like :word or addresses.handphone like :word or courses.name like :word",
{:word => "%#{keyword}%"}
],
:include => [:addresses, :gender, :course]
}
}

end

No comments:

Blog Archive