Are we supposed to be using Turbo Streams like this for every form submission?

By default with Rails 7 if you submit a form doing nothing extra than what’s created by the generators the form submission will be submit as TURBO_STREAM (verified in the console output after submitting the form). This isn’t broadcast to everyone (as expected).

However, based on the network tab in dev tools the form is handled by an HTML response that results in the entire HTML of the response being sent to the browser. Based on that response you could say the entire page is being re-rendered, perhaps through Turbo Drive.

I’m not sure if this assessment is correct but given that flash messages are usually set outside of your form’s partial that would mean maybe using Turbo Frames for form submissions wouldn’t be a good fit because it will involve also using Turbo Streams to render the flash message? In which case why not use Turbo Streams for both the form submission and updating the flash message?

With that said, does that mean this would be the ideal controller action to use in every single form you create if you wanted to take advantage of Turbo to improve the user experience and reduce load?

  def update
    respond_to do |format|
      if @user.update(user_params)
        flash[:notice] = "Updated successfully!"
        format.html { redirect_to user_path }
        format.turbo_stream { render_turbo_stream }
      else
        flash.now[:alert] = "Invalid form!"
        format.html { render :edit, status: :unprocessable_entity }
        format.turbo_stream { render_turbo_stream }
      end
    end
  end

  private

    # I know it's not a best practice to put 2 streams in a controller action,
    # normally you'd use a template but I did that here to make the code
    # sample more condensed.
    def render_turbo_stream
      render turbo_stream: [
        turbo_stream.replace(:flash, partial: "shared/flash"),
        turbo_stream.replace(:user_form, partial: "form", locals: { user: @user })
      ]
    end

Beyond that, the only addition in your ERB templates would be that you have id: "user_form" set on your form. No Turbo Frames required. In both the success and invalid case the html format is not being used for anything other than progressive enhancement right?

Overall though, would it be expected that to take advantage of Turbo we would have to do this for every form submission? Am I missing something?

If it is, does anyone have any tips on how to maybe reduce some boilerplate here? Also does anyone know why Hotwire is installed by default with Rails 7 but none of the generators are set up to use it?

Thanks!

2 Likes

Because it is an open source project, and anybody with time and knowledge about Rails can add something to improve it. :slight_smile: