Showing posts with label searchlogic. Show all posts
Showing posts with label searchlogic. Show all posts

Monday, September 13, 2010

Sorting searchlogic results


params[:filter][:order] = "ascend_by_created_at"
@search = Note.search(params[:filter])
@notes = @search.all

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

Table sort with Searchlogic

Searchlogic comes with a nice rails helper method to assist sorting of your paginated tables

<%= order @search, :by => :created_at, :as => "Created" %>

You don't even have to do anything extra to your controller to get some nice sorting action. Cool!

Using Searchlogic and Will Paginate

Here's the code to in controller to integrate the searching with binarylogic-searchlogic gem and pagination using mislav-will_paginate gem.

def index
@search = Enrollment.search(params[:search])
@enrollments, @enrollments_count = @search.paginate(:page => params[:page], :per_page => 20), @search.count
end