Masatoshi Nishiguchi

Search form using pg_search gem

This is my memo on Search form using pg_search gem.

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?
    then 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?s
      @artists = Artist.perform_search(params[:search])
    else
      @artists = Artist.all
    end
  end
# ...

references

Detecting enter key pressed in JavaScript

This is my memo on Detecting enter key pressed in JavaScript.

Vanilla JS

// Listen for the enter key press.
document.body.addEventListener( 'keyup', function (e) {
  if ( e.keyCode == 13 ) {
    // Simulate clicking on the submit button.
    submitButton.click();
  }
});

Vanilla JS

// Listen for the enter key press.
document.body.addEventListener( 'keyup', function (e) {
  if ( e.keyCode == 13 ) {
    // Simulate clicking on the submit button.
    triggerEvent( submitButton, 'click' );
  }
});

/**
 * Trigger the specified event on the specified element.
 * https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
 * https://codepen.io/felquis/pen/damDA
 * @param  {Object} elem  the target element.
 * @param  {String} event the type of the event (e.g. 'click').
 */
function triggerEvent( elem, event ) {

  // Create the event.
  var clickEvent = new Event( event );

  // Dispatch the event.
  elem.dispatchEvent( clickEvent );
}

jQuery

$( 'body' ).on( 'keyup', function( evt ) {
  if ( evt.keyCode == 13 ) {
    // Simulate clicking on the submit button.
    $button.trigger( 'click' );
  }
});