Masatoshi Nishiguchi
Software Engineer

Search form using pg_search gem

rails postgresql database search

Implementing search using pg_search gem

Screenshot 2015-07-18 21.51.47.png

Environment

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

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

/...
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
# ...

References