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.
app/controllers/users_searches_controller.rb
app/javascript/controllers/live_search_controller.js
app/javascript/controllers/toggle_controller.js
app/models/user.rb
app/views/shared/_user_switcher.html.erb
app/views/users_searches/_form.html.erb
app/views/users_searches/index.html.erb
app/views/users_searches/_none.html.erb
app/views/users_searches/_user.html.erb
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
<%= tag.div(class: "mr-2 relative", data: { controller: "toggle", toggle_toggle_class: "hidden" }) do %> <%= tag.button(class: "flex space-x-1 items-center cursor-pointer rounded rounded-b-none py-2 px-3 border-b border-transparent hover:bg-gray-100 hover:border-gray-200", data: { action: "click->toggle#toggle click@window->toggle#hide pagehide@window->toggle#hide" }) do %> <%= tag.span(user.full_name, class: "text-lg font-semibold max-w-xs truncate") %> <%= tag.span(class: "fa fa-caret-down text-blue-500") %> <% end %> <%= tag.div(class: "hidden z-40 origin-top-right absolute left-0 mt-1 w-60 rounded border border-gray-300 shadow-lg p-2 bg-white", data: { toggle_target: "toggleable" }) do %> <%= render partial: "users_searches/form" %> <% end %> <% end %>
This switcher dropdown might be loaded within a navbar.