Search form using pg_search gem
This is my memo on Search form using pg_search gem.
Implementing search using pg_search gem
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 usepg_search
gem. - Define
pg_search_scope
Whensearch
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?
then 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?s
@artists = Artist.perform_search(params[:search])
else
@artists = Artist.all
end
end
# ...