Search navigation with Turbo

Hey @Michael_L! I actually put together an example repo for exactly this functionality in another thread. Here’s a link to the sample code.

To break down the important parts, first I have a search form that I have on the index page of my resource.

<%= form_tag('/search', method: :get, data: { controller: "search" }) do %>
  <%= text_field_tag :search, params[:search], data: { action: "input->search#findResults" } %>
<% end %>
<div id="books"></div>

Then I created a stimulus controller that submits the form using the following code.

// app/assets/javascripts/controllers/search_controller.js

import { Controller } from "stimulus"

export default class extends Controller {
  findResults(event) {
    this.element.requestSubmit();
  }
}

Next, I have a search controller that processes the request that the form dispatches.

# app/controllers/search_controller.rb
class SearchController < ApplicationController
  def search
    @books = Book.search_title(params[:search])

    respond_to do |format|
      format.turbo_stream
      format.html         { redirect_to root_url(search: params[:search]) }
    end
  end
end

Finally, I have a turbo-stream template that populates the search results.

<turbo-stream action="update" target="books">
  <template>
    <ul>
      <% @books.each do |book| %>
        <%= content_tag :li, book.title %>
      <% end %>
    </ul>
  </template>
</turbo-stream>

You can find the full discussion of why I’m using methods like requestSubmit() and how we could limit the rate of requests in the full post here.

Hope this helps!

1 Like