LoginSignup
2
0

掲示板削除アクションのルーティングエラー解消

Last updated at Posted at 2024-01-30

エンジニア目指してプログラミングスクールでRuby,Rails勉強しながら奮闘中。
掲示板作成アプリ制作を通してつまづいた削除アクションのルーティングについてまとめる。

環境

ruby 3.14
rails 7.0.3.1
mac OS Sonoma 14.2.1
docker 24.0.7
docker compose v2.23.3-desktop.2

したいこと

作成した掲示板を削除して、掲示板一覧画面にリダイレクトしたい。

今回のポイント

  • destroyメソッドなどの必ず成功するべきメソッドには、!を付ける。
  • PUTやPOSTリクエスト後はリダイレクトのオプションでsee:otherを付けてステータスコード303を返す。

やってみたこと

boards_controllerでdestroyアクションを作成し、各行で以下を実現しようとした。

  • params[:id]を使ってboardsテーブルから該当のデータを取得
  • destroyメソッドを実行
  • 掲示板を削除しました。というフラッシュメッセージを表示
  • 掲示板一覧へリダイレクト
boards_controller.rb
  def destroy
    board = current_user.boards.find(params[:id])
    board.destroy!
    flash[:success] = t('defaults.flash_message.destroyed', item: t('activerecord.models.board'))
    redirect_to boards_path
  end

  private

  # ストロングパラメータ
  def board_params
    params.require(:board).permit(:title, :body, :user_id, :board_image)
  end
end

どんなエラー?

docker-compose
Started DELETE "/boards/33" for 192.168.65.1 at 2024-01-30 20:04:11 +0900
Processing by BoardsController#destroy as HTML
Parameters: {"id"=>"33"}

###中略####

# ここでdestroyアクションは成功しているっぽい。
Completed 302 Found in 32ms (ActiveRecord: 4.6ms | Allocations: 17375)

# なんかここで今度はDELETEメソッドを呼ぼうとしてる?
Started DELETE "/boards" for 192.168.x.x at 2024-01-28 20:10:56 +0900
# cannot render console?
Cannot render console from 192.168.x.x! Allowed networks: 127.0.0.0/127.255.255.255, ::1
# RoutingErrorが出ている。
ActionController::RoutingError (No route matches [DELETE] "/boards"):

Started GET "/boards" for 192.168.x.x at 2024-01-28 20:10:56 +0900
# cannot render console?
Cannot render console from 192.168.x.x! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by BoardsController#index as HTML

どうやって解決した?

ルーティングエラーになった件。

destroyメソッド完了後、同じ画面に戻ってこようとしているため、二重送信が行われてもう一度DELETEメソッドが呼ばれたのではないかと考察。二重送信時には掲示板のidが入っていないのでルーティングエラーになっている。

解決法
POSTメソッドの結果としてリダイレクトする際は
:see_otherを付け加えることで 別画面としてリダイレクトする 303レスポンスにする。

redirect_to boards_path :see_other

cannot render consoleが出ちゃう。

解決法
これは参考にさせていただいた記事の通りに、
config/environment/development.rbに以下ホワイトリストを追記した。

Rails.application.configure do
...略
  config.web_console.whitelisted_ips = '198.168.x.x' #追記
...略
end

結果

エラーなし! やったぜ。

docker-compose
Completed 303 See Other in 32ms (ActiveRecord: 12.8ms | Allocations: 10421)
 
 
Started GET "/boards" for 192.168.x.x at 2024-01-30 20:04:11 +0900
Processing by BoardsController#index as HTML

参考にさせていただいたサイト

2
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
2
0