1
1

More than 1 year has passed since last update.

【Rails】【メモ】記事削除をしたときに、destoroyメソッドが効かなかったときになんとかした時の対処方法

Posted at

環境

  • Mac(12.2.1)
    • MacBook Pro (13-inch, 2020)
    • 2 GHz クアッドコアIntel Core i5
    • 16 GB 3733 MHz LPDDR4X
  • ruby (3.0.0p0)
  • rails (7.0.1)
  • mysql2 (0.5.3)

はじめに

前提知識

解決したい内容

下記の削除ボタンを押したときに下記現象が起きた
・dstroyメソッドが効かず、GETメソッドを取得し、同ページに移動するだけ
・createメソッドが反応してしまい、各スコアが0のパターンの診断結果が記録される

image.png

image.png

protect_from_forgeryのが未設定であった

egograms_contoroller.rb
def destroy
    @ego_score= EgoScore.find(params[:id])
  if @ego_score.destroy
    flash.now[:success] = "削除しました"
    redirect_to action: :index
  else
    flash.now[:alert] = "削除に失敗しました"
    render "index"
  end
end

【エラー】ActionController::InvalidAuthenticityToken in EgogramsController#destroy

Can't verify CSRF token authenticity.
Extracted source (around line #251):

    def handle_unverified_request
      raise ActionController::InvalidAuthenticityToken, warning_message
    end
  end
end

Parameters:

{"_method"=>"delete", "authenticity_token"=>"[FILTERED]", "id"=>"78"}

改善内容

egograms_controller.rb
class EgogramsController < ApplicationController
#追記
    protect_from_forgery :except => [:destroy]

なぜ起きたか

CSRF(CrossSiteRequestForgery)対策
Railsでは、そのCSRF対策(外部からのアクセス遮断)を自動生成されている(=デフォルトで入っている)
今回は外部サイトからのAPIリクエストと認識されたようで、受け付けないらしい

参考
https://railsdoc.com/page/protect_from_forgery

Railsでlink_to deleteメソッドが動かない
https://qiita.com/mami3sansan/items/6a9710b3ffdc937aa5f3

パターン2 Routing Error

No route matches [DELETE] "/egograms"
Rails.root: /Users/syoichi/PF

Application Trace | Framework Trace | Full Trace
Routes
Routes match in priority from top to bottom

Helper HTTP Verb Path Controller#Action
egogram_path DELETE /egograms/:id(.:format) egograms#destroy

Parameters:

{"_method"=>"delete", "authenticity_token"=>"[FILTERED]"}

改善前

routes.rb
resources :egograms, only: [:new,:index,:edit,:destroy]
egograms/index.html.erb
<%= button_to '削除', egograms_path,action:"destroy",controller: "egograms", method: :delete, data: {confirm: "削除しますか?"} %>

改善後

egograms/index.html.erb
<%= button_to '削除', "egograms/#{i.id}",action:"destroy",controller: "egograms", method: :delete%>

もう一つ

rails7からはlink_toではなくbutton_toで作成しないと今回のエラーが起きる

パターン3 削除ボタンを押してもindexに戻るだけ

改善前後

routes.rb
resources :egograms, only: [:new,:index,:edit]

routes.rb
resources :egograms, only: [:new,:index,:edit,:desroy]
routes.rb
delete 'egograms/:id' => 'egograms#destroy'

routes.rb
#削除
# delete 'egograms/:id' => 'egograms#destroy'

その他:rails7からconfirmの使い方が変わっている

以前.
data: {confirm: "本当に削除しますか?"} 
rails7から.
form: { data: { turbo_confirm: "本当に削除しますか?" } } 
※form_withを使用する場合はこれ

参考
https://y-i.jp/entry/rails7-form-data-confirm
https://techracho.bpsinc.jp/hachi8833/2022_01_27/115075

1
1
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
1
1