TIL: How to do Modals with Turbo and Responders

Henrik Hauge Bjørnskov

--

I can’t even remember when I started using the responders gem. But to me it provides a very nice abstraction on the “tedious” respond_to blocks that a normal controller contains.

However it have been a struggle to find a solution to use it with Turbo when doing Modals.

As with most Rails things there exists a simple way of making it work.

  1. Make sure that ApplicationController contains self.respond_to :html, :turbo_stream.
  2. Add def to_turbo_stream = to_html to ApplicationResponder.
  3. Create a new.turbo_stream.erb template for your Controller. Responder will render this when a form is failing.
  4. Set data: { turbo_target: '_top' } on your form_with.
    This will make sure the redirect works as expected and no “Content Missing” errors will popup.

Your template should include something like the following

<%= turbo_stream.replace "your_form" do %>
<%= render 'form', my_model_resource: @my_model_resource %>
<% end %>

Does this solution add more boiler plate in the form of an extra template? Yes, but it also makes sure we don’t need to listen for events etc.

--

--

Henrik Hauge Bjørnskov
Henrik Hauge Bjørnskov

Written by Henrik Hauge Bjørnskov

I build stuff at Relatel A/S, vivid traveller and gear junkie.

No responses yet