Delete link_to with turbo_confirm and HTML redirect

Edit:

Turns out the issue was that i was using “@hotwired/turbo-rails”: “^7.1.1”. After updating to “@hotwired/turbo-rails”: “^7.3.0” link_to worked with turbo_stream.

<%= link_to @title, @url, class: "text-blue", data: { turbo_stream: true } %>


I’m trying to delete an article via link_to or button_to and afterwards redirect to another page (e.g. html response). Before I want to present the turbo_confirm dialog (I know I can use UJS but what’s the point of having UJS just for this?).

<%= link_to "Delete", admin_article_path(@article, redirect_to: admin_articles_path, format: :html), data: { turbo_method: :delete, turbo_confirm: "are you sure?" }, class: "action-button" %>
<%= button_to "Delete Article", admin_article_path(@article, redirect_to: admin_articles_path, format: :html), method: :delete, data: { turbo_method: :delete, "turbo_confirm": "Are you sure?" }, form: { data: { turbo_method: :delete, turbo_confirm: "Sure?" } }, class: "secondary-button" %>

I can’t figure out how do something so simple. I seem to always trigger a turbo_stream response. Does somebody know how to use turbo_confirm together with a HTML response? Or is there another best practice for that.

My controller action looks like below because when I delete from the index page I want to trigger a turbostream, but when I delete from the show page, I want a normal HTML redirect after deletion.

  def destroy
    article.destroy

    referer = params[:redirect_to] || request.referer || root_path

    respond_to do |format|
      format.html { redirect_to referer, status: 301 }
      format.turbo_stream { }
    end
  end

Edit:
When I change the line:
format.html { redirect_to referer, status: 301 }

to this:
format.html { redirect_to referer + "?format=html", status: 301 }

it works. But there must be a simpler less way?

1 Like