Skip to content

Instantly share code, notes, and snippets.

@rderoldan1
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rderoldan1/9478893 to your computer and use it in GitHub Desktop.
Save rderoldan1/9478893 to your computer and use it in GitHub Desktop.
Example of search methods in Postgresql
# app/helpers/application_helper.rb
module ApplicationHelper
# Search form tag, render html form for bootstrap 3
# params
# - path, url of controller action: clients_path
# - placeholder text: 'Search by Name or Nickname'
# Return
# HTML safe string
def search_form(path, placeholder)
form_tag path, class: "well", :method => 'get' do
content_tag :div, class: 'row' do
content_tag :div, class: 'col-md-6' do
content_tag :div, class: 'input-group' do
text_field_tag(:finder, params[:finder], :class => "form-control input-sm", :placeholder => placeholder)+
content_tag(:span, class: 'input-group-btn') do
submit_tag("Search", :class => 'btn btn-success btn-sm spin')
end
end
end
end
end
end
end
# app/models/client.rb
class Client < ActiveRecord::Base
# Include Searchable concern
include Searchable
end
# app/controllers/clients_controller.rb
@clients = Client.search(params[:finder], params[:page], ['name', "nickname", "email", "date"])
<!--app/views/clients/index.html.erb -->
<%= search_form(cients_path, "Search by Name or Nickname" ) %>
# app/models/concerns/searchable.rb
module Searchable
extend ActiveSupport::Concern
module ClassMethods
# Search method basen in will_paginate gem
# params
# - string pattern: "Jhon"
# - integer page: 10
# - array of attribute names as string: ['name', 'email', 'nickname']
# Return
# Wil paginate records
def search(pattern, page, attr)
paginate :per_page => 20, :page => page,
:conditions => string_builder(attr, pattern)
end
private
# Build string search and params for conditions based in attributes
# params
# - array of attribute names as strings: ['name', 'email', 'nickname']
# - string pattern: "Jhon"
# Return
# ["UPPER(cast(name)), UPPER(cast(email)), UPPER(cast(nickname)) LIKE ? or ? or ?", "%Jhon%", "%Jhon%", "%Jhon%"]
def string_builder(attr, pattern)
finder ||= ""
arr = []
arr << attr.map{|att| " UPPER(cast(#{att} as text)) LIKE ?"}.join(' or')
arr << attr.map{|att| '%'+pattern.upcase+'%'}
arr.flatten
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment