method: :delete on link_to in Rails 7

From Rails 4 (?) until Rails 6.1, you have Rails UJS in both default setups for Webpacker and Sprockets available. UJS does some magic left and right. One of that magic is the following: You can define a link_to element in your code as follows:

= link_to "Löschen", server_path(server), method: :delete, class: "pl-8"

This will turn into the following HTML:

<a class="pl-8" rel="nofollow" data-method="delete" href="/servers/c6a580a4-f855-5413-9181-70f1a5a256e9">Löschen</a>

Upon clicking this element, Rails UJS will intercept the request and replace the link with a proper form in case data-method is set. You can check out the relevant code here.

If you start a new Rails 7 app with importmaps, UJS won’t be there. You could add UJS via the import maps, but you can actually use button_to to solve this scenario.

= button_to "Löschen", server_path(server), method: :delete, form_class: "pl-8 inline"

This will result in the following HTML:

<form class="pl-8 inline" method="post" action="/servers/c6a580a4-f855-5413-9181-70f1a5a256e9">
  <input type="hidden" name="_method" value="delete">
  <button type="submit">Löschen</button>
  <input type="hidden" name="authenticity_token" value="dcOVJmD5M7FX5Iu1RsLj5exziAJ8Z9aKCxs2AITUXvX-mbemDEzdbMX2-6SOu8_AliDGlSHEmRiT1ahcOkviNQ">

As you can observe, Rails will insert an entire form when declaring button_to. With form_class: inline we can ensure that the form will be inlined as a normal link would as well.