2

I've incorporated Hotwire into my latest Rails 6 app. The Hotwire/Turbo portions are working great, but I have a plain user form that I don't want to use Hotwire/Turbo for. Currently, all form submissions are hitting format.turbo_stream {} in my controller , but I want this particular form to hit the format.html {} block instead. I noticed that the Accept header on form submission requests automatically includes text/vnd.turbo_stream.html now, but I'm not sure how to remove this.

The form is not wrapped in a turbo_frame_tag; there is no Turbo anywhere on the page, and it looks pretty standard:

    <%= form_with model: @user do |f| %>
      <%= f.file_field :avatar, class: "file-input", id: "avatar-input" %>
      <%= f.text_field :name, class: "input wide", placeholder: "Your name here" %>

      <%= f.submit "Next", class: "button-next-submit" %>
    <% end %>

How do I force this change on a per-form basis? I previously thought that adding the turbo tags was how you change the behavior / the Accept header, but I see now that once you add a format.turbo_stream block in your controller method, the form begins to prefer it.

aidan
  • 1,627
  • 17
  • 27

2 Answers2

1

Figured it out. It looks like most form helpers (form_with, form_for, etc) accept a format param in the option hash (documentation link). The value you provide should match the format.x block you wish to hit in your controller. E.g.:

# view.html.erb
<%= form_with model: @user, format: :html do |f| %>
...
<% end %>

# controller.rb

def update
  ...
  respond_to do |format|
    format.html {} # format: :html will hit this
    format.turbo_stream {} # format: :turbo_stream will hit this
    # format.json is also an option
  end
end
aidan
  • 1,627
  • 17
  • 27
1

In my case (rails 7) format: :html wasn't enough. What works for me was turbo: false

# view.html.erb
<%= form_with model: @user, data: { turbo: false } do |f| %>
...
<% end %>

# controller.rb

def update
  ...
  respond_to do |format|
    format.html {} # format: :html will hit this
    format.turbo_stream {} # format: :turbo_stream will hit this
    # format.json is also an option
  end
end
Pedro Gabriel Lima
  • 1,122
  • 1
  • 9
  • 24