0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

更新ボタンが削除ボタンとして機能してしまう

Last updated at Posted at 2021-08-04

「更新する」ボタンを押したら、ユーザーが削除される現象が起きてしまい、原因がわかったのでメモ。

状態

編集内容を入力後、「更新する」を押すとユーザーが削除された。

スクリーンショット 2021-08-04 13.58.00.jpg

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  ・
  ・
  <div class="actions mt-3 text-center">
     <%= f.submit "更新する", class: "btn btn-primary" %>
    <%= button_to "削除する", registration_path(resource_name), data: { confirm: "本当によろしいですか?" }, method: :delete, class: "btn btn-danger" %>
  </div>
  ・
  ・
<% end %>

原因

以下のように「更新する」を押した際にDELETEリクエストが送信されていた。

スクリーンショット 2021-08-04 14.04.38.jpg

対策1: フォームの外にbutton_toを設置

button_toではlink_toと違いフォームを作り、その中にinputタグでボタンが生成されるものだそう。
そのため、formの外で使用しないと思うようなbutton_toの役割ができないみたい。
フォームの外にbutton_toを設置することで「更新する」が正常に動作した。
[【Rails】 button_toの使い方をどこよりもわかりやすく解説!]
(https://pikawaka.com/rails/button_to#link_to%E3%81%A8%E3%81%AE%E9%81%95%E3%81%84)

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  ・
  ・
  <div class="actions mt-3 text-center">
     <%= f.submit "更新する", class: "btn btn-primary" %>
  </div>
  ・
  ・
<% end %>
<%= button_to "削除する", registration_path(resource_name), data: { confirm: "本当によろしいですか?" }, method: :delete, class: "btn btn-danger" %>

スクリーンショット 2021-08-04 14.25.23.jpg

対策2: button_toをlink_toに変更

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  ・
  ・
  <div class="actions mt-3 text-center">
     <%= f.submit "更新する", class: "btn btn-primary" %>
    <%= link_to "削除する", registration_path(resource_name), data: { confirm: "本当によろしいですか?" }, method: :delete, class: "btn btn-danger" %>
  </div>
  ・
  ・
<% end %>

スクリーンショット 2021-08-04 14.27.26.jpg

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?