Rails: Update DOM with partial


In my scenario, there is a list of items and a search field. I want to update the list of items with elements filtered with the search term.

I have a working solution right now, but I think there should be a better solution.
I’m using Kaminari for Pagination as well and this works by

  1. Setting remote=true
  2. In the controller, filtering the elements @surveys = Survey.where(...).page(...).per(...)
  3. Respond to js with a .js.erb: format.js { render :update_list }
  4. In update_list.js.erb replacing the list with a new list rendered with the partial and the new elements: document.getElementById("surveys").innerHTML = "<%= j render(partial: 'surveys', locals: { surveys: @surveys }) %>"

In order to include search as well, I have created a Stimulus Controller that performs an AJAX call with the search term as parameter and Accept: Javascript header, so that the controller responds the same way as for a pagination.

The problem is, I would also like show additional information when searching, e.g. the number of records matching the search query. Right now, Stimulus is not even involved with updating the DOM, that happens as “side effect”

I feel like there should be a way to request the filtered elements via Stimulus, render the partial into the correct div AND then update additional information.

How can this be done?

Maybe try rethinking your problem a bit. I have a very similar page in a Rails project that does what you describe and does not need Stimulus at all. Unless I’m missing what you are trying to do, your problem can be solved solely with rails-ujs and turbolinks.

Your current solution seems overly complex. Start by implementing this without manually doing any JS, just let Turbolinks do it’s thing. Get the minimum working without first, then bring Stimulus in if you really need it.

1 Like

You are right, in the meantime I figured out how to solve it without Stimulus. The problem was that initially, I didn’t have the Searchfield in a Form.