User Live Search with Stimulus, Turbo Frames and PgSearch

Curated ago by @jeremysmithco

Description

Here’s a solution I’ve used on a project to add a user switcher dropdown with typeahead search to a navbar. It uses the pg_search gem for Postgres full-text search.

There are a lot of blog posts out there with similar solutions, with terms like: typeahead, autocomplete, autosuggest, instant search.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class UsersSearchesController < ApplicationController
  def index
    @users = users_query(params[:query])

    respond_to do |format|
      format.html
    end
  end

  private

  def users_query(search_query)
    base_query = current_account.users
    return base_query.user_search(search_query).limit(10) if search_query.present?

    base_query.order(:last_name, :first_name)
  end
end

The search is implemented on the #index action as a GET request with optional query param.