Last active
August 29, 2015 14:11
-
-
Save scruwys/4356c41d45d2809c5010 to your computer and use it in GitHub Desktop.
quick and dirty search for ActiveRecord
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # app/models/product.rb | |
| class Product < ActiveRecord::Base | |
| simple_search | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # app/controllers/products_controller.rb | |
| class ProductsController < ApplicationController | |
| # GET /products | |
| def index | |
| @jobs = Products.search([:name, :description], params[:q], params[:page], 10) | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.