Masatoshi Nishiguchi
Masatoshi Nishiguchi's Blog

Masatoshi Nishiguchi's Blog

Search form using pg-search gem

Masatoshi Nishiguchi's photo
Masatoshi Nishiguchi
·Jun 27, 2016·

2 min read

This is my memo about implementing basic search form using pg_search gem.

Implementing search using pg_search gem

Screenshot 2015-07-18 21.51.47.png

Environment

  • Ruby
  • Rails
  • PostgreSQL
  • pg_search gem

Gemfile

gem 'rails'
gem 'pg'
gem 'pg_search',   '~> 1.0.3'   # Named scopes that take advantage of PostgreSQL's full text search
# ...

Get started

Model

  • Add include PgSearch to use pg_search gem.
  • Define pg_search_scope When search method is called, searching will be performed based on the scope that is defined here.
class Artist < ApplicationRecord
  include PgSearch

  has_many :songs, dependent: :destroy

  scope :sorted, ->{ order(name: :asc) }

  pg_search_scope :search,
                  against: [
                    :name,
                    :nationality
                  ],
                  using: {
                    tsearch: {
                      prefix: true,
                      normalization: 2
                    }
                  }

  def self.perform_search(keyword)
    if keyword.present?
      Artist.search(keyword)
    else
      Artist.all
    end.sorted
  end
end

View

  • Create a search form.
  • Issue a GET#index request with the user's input as a search term.
/...
h1.page-header All the Artists

.artist_search.form-group
  = form_tag(artists_path, method: "get") do
    = text_field_tag :search, nil, placeholder: "Search artists ...", class: "form-control"
    = submit_tag "", style: "display: none;"
/...

Controller

class ArtistsController < ApplicationController
  def index
    if params[:search].present?
      @artists = Artist.perform_search(params[:search])
    else
      @artists = Artist.all
    end
  end
# ...

Resources

 
Share this