Skip to content

Instantly share code, notes, and snippets.

@scruwys
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save scruwys/4356c41d45d2809c5010 to your computer and use it in GitHub Desktop.

Select an option

Save scruwys/4356c41d45d2809c5010 to your computer and use it in GitHub Desktop.
quick and dirty search for ActiveRecord
# app/models/concerns/simple_search.rb
module SimpleSearch
extend ActiveSupport::Concern
module ActiveRecord
def simple_search
include SimpleSearch
end
end
included do
EXCLUDED_WORDS = ['a', 'the', 'or', 'and', 'of', 'have', 'to', 'it', 'that', 'for',
'with', 'on', 'do', 'say', 'this', 'he', 'she', 'you', 'they', 'but', 'we', 'from']
def self.search(fields, search_query, page, per_page = 5)
if search_query.nil?
records = self.order(self.display_field)
else
records = []
terms = build_search_query(search_query)
query = build_fields_query(fields)
terms.each { |t| records.push(*where(query, term: t)) }
end
paginate(records, page, per_page)
end
protected
def self.paginate(records, page, per_page = 5)
if records.kind_of?(Array)
records = Kaminari.paginate_array(records)
end
records.page(page).per(per_page)
end
def self.build_fields_query(fields)
if fields == :all
fields = self.column_names - ['id', 'created_at', 'updated_at', 'deleted_at']
end
fields.map { |f| "#{f.to_s} ILIKE :term" }.join(" OR ")
end
def self.build_search_query(search_query)
terms = search_query.split(' ') - EXCLUDED_WORDS
terms.collect { |t| "%#{t}%" }
end
end
end
# app/models/product.rb
class Product < ActiveRecord::Base
simple_search
end
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
# GET /products
def index
@jobs = Products.search([:name, :description], params[:q], params[:page], 10)
end
end
@scruwys
Copy link
Author

scruwys commented Dec 9, 2014

quick and dirty, not super efficient, but thought I'd share anyway. I thought it'd be useful for instances where you need search but don't want to use a heavier alternative like ElasticSearch or Solr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment