Oba-eng / curry_web

0 stars 0 forks source link

削除機能が機能しない #19

Open Oba-eng opened 7 months ago

Oba-eng commented 7 months ago

routes.rb Rails.application.routes.draw do root 'menus#index'

resources :menus do resources :favorites, only: [:create, :destroy] end

resources :users resources :menus do collection do get :favorites end end resources :favorites, only: %i[create destroy]

namespace :mypage do resources :tree, only: [:index] end

resources :sessions, only: [:new, :create, :destroy]

delete 'logout', to: 'sessions#destroy' get 'logout', to: 'sessions#destroy', as: :logout_get

フッターのリンクを作成

get 'privacy', to: 'pages#privacy', as: :privacy get 'terms', to: 'pages#terms', as: :terms

お問い合わせメール

namespace :public do resources :contacts, only: [:new, :create] do collection do post 'confirm' post 'back' get 'done' end end end

devise_for :users

end

menus_controller.rb class MenusController < ApplicationController before_action :set_menu, only: %i[ show edit update destroy ] skip_before_action :require_login, only: %i[index]

def index @menus = Menu.all @q = Menu.ransack(params[:q]) @menus = @q.result(distinct: true).includes(:user).page(params[:page]).order("created_at desc") end

def show @q = Menu.ransack(params[:q]) end

def new @menu = Menu.new @q = Menu.ransack(params[:q]) end

def edit @menu = Menu.find(params[:id]) @q = Menu.ransack(params[:q]) end

def create @q = Menu.ransack(params[:q]) @menu = current_user.menus.new(menu_params)

  if @menu.save
    redirect_to menus_path, success: '保存しました'
  else
    render :new
  end

end

def update @q = Menu.ransack(params[:q]) respond_to do |format| if @menu.update(menu_params) format.html { redirect_to menu_url(@menu), success: '更新しました' } format.json { render :show, status: :ok, location: @menu } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @menu.errors, status: :unprocessable_entity } end end end

def destroy menu = Menu.find(params[:id]) menu.destroy redirect_to menus_url, notice: '削除しました' end

def favorites @favorites_menus = current_user.favorite_menus.includes(:user).order(created_at: :desc) end

private def set_menu @menu = Menu.find(params[:id]) end

def menu_params
  params.require(:menu).permit(:name, :material, :make, :point, :menu_image, :menu_image_cache)
end

end



- エラーから考えられる原因
ログが発生しないため何から手をつけていいか分からず手が止まっています。
chatGPTからJavaScriptが関係しているのではないかと回答が返ってきているため
ここが原因かとも考えましたが
JavaScriptの何が起因しているのか見当もつかないです。
(現在お気に入り機能でもエラーが発生しておりここでもJavaScriptが原因ではないかと回答が返ってきてます。)

- 試したこと
管理者ツールからエラーがないか確認
→エラーなし
chatGPTに質問
→コントローラー、ビュー、ルートには問題なし
削除機能の流れをGoogleで検索しながら確認
→問題なし
kenchasonakai commented 7 months ago

Railsのバージョンなどの情報や、参考にした記事の情報の共有をお願いします

Oba-eng commented 7 months ago

バージョン情報 Rails 5.2.8.1 ruby 2.6.5

参考記事 https://qiita.com/STHEXA/items/bebd35d67013fe0f19dd

参考記事は「rails 削除機能」と調べて一番上に出てきたものを参考にしてます。他にも何個か記事を見ながら進めましたが 一番参考にしている記事を載せてます。 念のため下記に他のURLも載せておきます。 https://qiita.com/super-kiricub/items/3981b50828383cdab40a https://nakaharabo.com/rails-delete

kenchasonakai commented 7 months ago

ありがとうございます! 5系を使ってるんですね(5系は公式のサポートが終了しているので7系を使うのがおすすめではあります)

削除ボタンを押した時のログも共有していただいて良いでしょうか

Oba-eng commented 7 months ago

ひと段落ついたら7系に変更してみます。

Started GET "/menus/13" for ::1 at 2024-03-04 15:26:52 +0900
Processing by MenusController#show as HTML
  Parameters: {"id"=>"13"}
  Menu Load (0.3ms)  SELECT  "menus".* FROM "menus" WHERE "menus"."id" = ? LIMIT ?  [["id", 13], ["LIMIT", 1]]
  ↳ app/controllers/menus_controller.rb:62
  Rendering menus/show.html.erb within layouts/application
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:9
  CACHE User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/views/menus/show.html.erb:60
   (0.4ms)  SELECT COUNT(*) FROM "menus" WHERE "menus"."user_id" = ?  [["user_id", 1]]
  ↳ app/views/menus/show.html.erb:64
  Rendered menus/show.html.erb within layouts/application (15.5ms)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered shared/_search.html.erb (1.1ms)
  Rendered shared/_header.html.erb (3.1ms)
  Rendered shared/_flash_message.html.erb (0.4ms)
  Rendered shared/_footer.html.erb (0.7ms)
Completed 200 OK in 67ms (Views: 60.5ms | ActiveRecord: 1.2ms)

今気づいたのですが、ログでGETメソッドが働いているのでここが問題なのでしょうか? 本来ならdeleteメソッドが反応するはず?

<%= link_to '削除', menu_path(@menu.id),method: :delete %>

kenchasonakai commented 7 months ago

Started GET "/menus/13" for ::1 at 2024-03-04 15:26:52 +0900

showにリクエストが飛んでるっぽいですね 検証ツールのconsoleタブに何かエラーが出ていないか見てみてください また、削除リンクが実際にどんなHTMLになっているかelementタブを確認してみても良いかと思います

Oba-eng commented 7 months ago

Image from Gyazo

コンソールタブにエラーはなく、HTMLは "/menus/13"となっています。 binding.pryをshowアクションに入れたらデバッカーが反応したので間違いなくshowアクションが動いている事は確認しました。 で、結局showアクションが動いてしまっているのはどうしてだ?となって止まっているのですが、 Image from Gyazo ルートを確認してもHTMLは間違っていないように見えます、、、。

kenchasonakai commented 7 months ago

他のルーティングでdeleteリクエストが動いているものはありますか?

Oba-eng commented 7 months ago

他のルーティングでDELETEリクエストが動いているものは確認できませんでした。 気になったのはログアウトする時のログです。 rails routesでルートを確認しログアウトの部分を下記に抜粋しました。 DELETEとGETが両方設定されておりGETの方が使用されている状況です。

DELETE /logout(.:format) sessions#destroy
GET    /logout(.:format) sessions#destroy
Started GET "/logout" for ::1 at 2024-03-06 15:06:29 +0900
Processing by SessionsController#destroy as HTML
Redirected to http://localhost:3000/sessions/new
Completed 302 Found in 3ms (ActiveRecord: 0.0ms)

Started GET "/sessions/new" for ::1 at 2024-03-06 15:06:29 +0900
Processing by SessionsController#new as HTML
  Rendering sessions/new.html.erb within layouts/application
  Rendered sessions/new.html.erb within layouts/application (5.7ms)
[Webpacker] Everything's up-to-date. Nothing to do
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:9
  Rendered shared/_search.html.erb (0.8ms)
  CACHE User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:9
  Rendered shared/_header.html.erb (3.2ms)
  Rendered shared/_flash_message.html.erb (0.3ms)
  Rendered shared/_footer.html.erb (0.4ms)
Completed 200 OK in 78ms (Views: 73.7ms | ActiveRecord: 0.2ms)

また、ルーティングファイルを確認し下記の該当部分を削除してもう一度ログアウトをしてみたらエラーが発生しました。

 delete 'logout', to: 'sessions#destroy'
  get 'logout', to: 'sessions#destroy', as: :logout_get

Image from Gyazo

どの場面でもDELETEリクエストが送信されずGETリクエストになってしまっているようです。

kenchasonakai commented 7 months ago

ありがとうございます 5系を使っている&DELETEリクエストが送られていないとのことなのでrails-ujsというリンクから送られるリクエストをDELETEやPUTなどのGET・POST以外の形式として送信するものが動いていないのかなと思うのでJavaScriptのファイル周りでujsの設定がちゃんと出来ているか確認してあげると良いかなと思います

https://www.inodev.jp/entry/2019/12/03/234210

Oba-eng commented 7 months ago

送っていただいた記事を参考にrails-ujsについて調べてみた結果、正しくimportされていないことが発覚しました。

app/javascript/pasks/apllication.js
import Rails from "@rails/ujs";
/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

console.log('Hello World from Webpacker')

import Rails from "@rails/ujs";を追加。

app/views/layouts/application.html.erb<%= javascript_pack_tag 'application' %>が記載されいるのも確認し正しく読み込まれている状況です。

もう一度削除ボタンをクリックしてみましたがGETメソッドでリクエストされてしまってます。

Started GET "/menus/13" for ::1 at 2024-03-07 23:34:54 +0900
Processing by MenusController#show as HTML
  Parameters: {"id"=>"13"}
  Menu Load (0.2ms)  SELECT "menus".* FROM "menus" WHERE "menus"."id" = ? LIMIT ?  [["id", 13], ["LIMIT", 1]]
  ↳ app/controllers/menus_controller.rb:62:in `set_menu'
  Rendering layout layouts/application.html.erb
  Rendering menus/show.html.erb within layouts/application
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:9:in `current_user'
  CACHE User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/views/menus/show.html.erb:60
   (0.3ms)  SELECT COUNT(*) FROM "menus" WHERE "menus"."user_id" = ?  [["user_id", 1]]
  ↳ app/views/menus/show.html.erb:64
  Rendered menus/show.html.erb within layouts/application (Duration: 6.7ms | Allocations: 2241)
[Webpacker] Compiling...
[Webpacker] Compiled all packs in /Users/oobarikuto/workspace/curry_web/-curry_web/carry_web/public/packs
[Webpacker] Hash: e5d2e3b46bb76238498b
Version: webpack 4.47.0
Time: 210ms
Built at: 2024/03/07 23:34:55
                                     Asset       Size       Chunks                         Chunk Names
    js/application-05aedb02e0d635e0472c.js   27.7 KiB  application  [emitted] [immutable]  application
js/application-05aedb02e0d635e0472c.js.map   30.9 KiB  application  [emitted] [dev]        application
                             manifest.json  364 bytes               [emitted]              
Entrypoint application = js/application-05aedb02e0d635e0472c.js js/application-05aedb02e0d635e0472c.js.map
[./app/javascript/packs/application.js] 879 bytes {application} [built]
    + 1 hidden module

  Rendered shared/_search.html.erb (Duration: 0.3ms | Allocations: 232)
  Rendered shared/_header.html.erb (Duration: 0.5ms | Allocations: 426)
  Rendered shared/_flash_message.html.erb (Duration: 0.0ms | Allocations: 18)
  Rendered shared/_footer.html.erb (Duration: 0.0ms | Allocations: 77)
  Rendered layout layouts/application.html.erb (Duration: 887.9ms | Allocations: 56248)
Completed 200 OK in 891ms (Views: 888.0ms | ActiveRecord: 0.7ms | Allocations: 57304)

上記は削除ボタンをクリックしたときのログです。 ujsの設定がうまくいっていないのか、違う部分に問題があるのかわかりません。 管理者ツールでエラーを確認しましたがエラーはありませんでした。 お手上げ状態なためアドバイスをいただきたいです。

kenchasonakai commented 7 months ago

webpackerで動かすならRails.startみたいな記述が必要かもですね https://paulownia.hatenablog.com/entry/2020/01/01/202628

Oba-eng commented 7 months ago
import Rails from "@rails/ujs";
Rails.start();
/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

console.log('Hello World from Webpacker')

Rails.start();を追加したら無事DELETEメソッドでリクエストが送信されました! ログアウトの時もDELETEメソッドで送信されていることも確認できました! ありがとうございます。