Oba-eng / curry_web

0 stars 0 forks source link

画像プレビューが表示されない #25

Open Oba-eng opened 5 months ago

Oba-eng commented 5 months ago

<% end %>

app/controllers/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

config/routes Rails.application.routes.draw do root 'menus#index'

resources :users do resources :menus end

resources :menus do member do post :favorite, to: 'favorites#create' end end

resources :menus do resource :favorite, only: [:destroy] end

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 end

app/assets/javascripts/common.js function previewImage() { const target = this.event.target; const file = target.files[0]; const reader = new FileReader(); reader.onloadend = function () { const preview = document.querySelector("#preview") if(preview) { preview.src = reader.result; } } if (file) { reader.readAsDataURL(file); } }

app/uploaders/menu_image_uploader.rb import Rails from "@rails/ujs"; Rails.start(); import Turbolinks from "turbolinks"; Turbolinks.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')


- エラーから考えられる原因
参考URLと同じコードで動いていないため
ビュー、JavaScriptのコード以外の何かが原因でエラーが発生しているのではないかと考えてます。
→JavaScriptの読み込みができていない?

- 試したこと
ファイルの格納場所を
```app/assets/javascripts/common.js```から
```app/javascript/common.js```に変更。

また、```javascript```のコードを別ファイルで用意するのではなく直接ビューファイルに記載し実行。
どちらもエラーさえ発生せず、JavaScriptのコードが走りすらしないという結果に終わっています。

https://www.notion.so/ca15999aca144044b718248373cce3e5?pvs=4#833ac732ead74e41b5da2aca726bd052
上記記事を参考にまずAsset Pipelineの機能を無効にするためapp/assets/javascript/ の配下にあるapplication.jsを編集。

application.jsの中に記載してある下記の一文を削除。

//= require_tree .


ファイルを読み込むためにimportを追加。

app/javascript/packs/apllication.js import Rails from "@rails/ujs"; Rails.start(); import Turbolinks from "turbolinks"; import "./common" ↑これを追加 Turbolinks.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')



- 参考URL
https://osamudaira.com/177/#toc13
https://papael14.com/ruby-on-rails-javascript/

- バージョン情報
Rails 6.1.4
ruby 3.0.2
gem 'carrierwave', '~> 2.0'
gem 'mini_magick'
Tsuchiya2 commented 5 months ago

Rails基礎の課題11に同様のカリキュラム・説明があったかと思うので復習してみると良いかもしれません。

Rails6系のJavaScriptの管理・使用の仕方を調べ、common.jsファイルがまず読み込まれる状態であるかを確認・仮説立て・検証のサイクルを回してみましょう。

まずはcommon.jsファイルに"console.log('Read:common.js)'"を書いて、ブラウザのコンソールに表示させるところから取り組む、最終的に期待している挙動になるところまで仮説立て・検証のサイクルを回していきましょう。

Oba-eng commented 5 months ago

ありがとうございます。解決しました。 まず、jQueryが読み込まれていなかったためコンソールにエラーが表示されていました。 https://www.notion.so/ca15999aca144044b718248373cce3e5?pvs=4#b380bfd323054c3bb9c488e61aba65d7 この記事を参考にjQueryの設定。コンソールのエラーは解消。

その後jsファイルは読み込みができていましたが、定義している関数が見つからないとエラーが発生したためjsの関数について調べた結果グローバルスコープとして定義していないため別ファイルからの呼び出しができない設定になっていました。 こちらを直したら無事プレビュー画像が表示されるようになりました。