TIL: How to do Modals with Turbo and Responders
1 min readFeb 15, 2025
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.
- Make sure that
ApplicationController
containsself.respond_to :html, :turbo_stream
. - Add
def to_turbo_stream = to_html
toApplicationResponder
. - Create a
new.turbo_stream.erb
template for your Controller. Responder will render this when a form is failing. - Set
data: { turbo_target: '_top' }
on yourform_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.