In the app I’m working on, there are two forms that post to the same Rails controller action. One of them wants a Turbo Stream response and the other wants a normal redirect.
Is there any way to opt out of Turbo Stream responses on a per form basis?
I don’t there’s any blessed way to do this. Turbo Drive will add a header to accept a turbo stream when you submit a form. If you have this header, Rails will trigger your format.turbo_stream block and not format.html.
To get around this, you could turn turbo off for that form by adding a data-turbo="false" attribute. Or you could include something in the form itself — I’m thinking a hidden input — that you can pick up with an if/else block in your controller.
respond_to do |format|
format.turbo_stream { render turbo_stream: turbo_stream.replace(@action) }
format.html { redirect_to actions_path }
end
The problem is I only want the Turbo Stream response when submitting one of the forms. I do however want to submit both forms with Turbo, to make sure they work with Turbo Native.
A hidden input is a great idea! A similar (Rails-specific) solution I came up with is to explicitly specify the html format in the URL the form submits to:
form_with url: actions_path(@action, format: :html) do |f|