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
<%= turbo_frame_tag "user_search" do %>
  <div data-live-search-target="loading" class="hidden">
    <p class="px-1 py-1 text-sm text-gray-500">Searching…</p>
  </div>

  <div data-live-search-target="results">
    <%= render(partial: "users_searches/user", collection: @users) || render(partial: "users_searches/none") %>
  </div>
<% end %>

The results render uses a trick to render the user partial if there are any @users returned, or fallback to the none partial.