前提
Railsでメモアプリを作っています。
複数のメモを同時に投稿したいため、JavaScriptでformに要素を追加しRailsで配列形式のparamsを送受信するといったことを考えています。
最終的には階層構造のメモアプリを作成したいですが、今はメモ一覧(階層なし)とメモ投稿の2ページのみです。
発生している問題・エラーメッセージ
new.html.erbにて
notes-valueにテキストを入力
notes-submitをクリック
→アドレスバーから移動/リロード していた場合
notes-listに子要素が追加
→application.html.erbのlink_toから移動 していた場合
notes-listに子要素が追加されず、下のエラーが表示
Uncaught TypeError: Cannot read properties of null (reading 'set')
該当のソースコード
routes.rb
1Rails.application.routes.draw do 2 3 root 'notes#index' 4 get 'notes/new' => 'notes#new' 5 post 'notes/create' => 'notes#create' 6 7end
notes_controller.rb
1class NotesController < ApplicationController 2 3 def index 4 @notes = Note.all 5 end 6 7 def new 8 end 9 10 def create 11 params[:notes].each do |text| 12 @note = Note.new(text: text) 13 @note.save 14 end 15 redirect_to("/") 16 end 17 18end
application.html.erb
1<!DOCTYPE html> 2<html> 3 <head> 4 <title>MemoApp</title> 5 <meta name="viewport" content="width=device-width,initial-scale=1"> 6 <%= csrf_meta_tags %> 7 <%= csp_meta_tag %> 8 9 <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> 10 <%= javascript_importmap_tags %> 11 </head> 12 13 <body> 14 <%= link_to "index", "/" %> 15 <%= link_to "new", "/notes/new" %> 16 <%= yield %> 17 </body> 18</html>
new.html.erb
1<form> 2 <input type="text" id="note-value"> 3 <button type="submit" id="note-submit">追加</button> 4</form> 5 6<form id="note-list" action="/notes/create" method="post"> 7 <button type="submit">作成</button> 8</form>
app/javascript/custom/script.js
1const noteValue = document.getElementById('note-value'); 2const noteSubmit = document.getElementById('note-submit'); 3const noteList = document.getElementById('note-list'); 4 5noteSubmit.addEventListener('click', e => { 6 e.preventDefault(); 7 const text = noteValue.value; 8 if(text) { 9 const note = `<input type="text" value=${text} name="notes[]"></input>`; 10 noteList.insertAdjacentHTML('afterbegin', note); 11 noteValue.value = ""; 12 } 13});
参考サイト/【JavaScriptの実践】TODOリストの作り方
JavaScript読み込み用に追加したコード
app/javascript/application.js
1import "./custom/script.js"
config/importmap.rb
1pin_all_from "app/javascript/custom", under: "custom"
参考サイト/Rails 7でJavaScriptファイルを読み込みたい
試したこと
jsをwindow.addEventListener('DOMContentLoaded', => {})で囲ってみる?
application.html.erbの<%= javascript_importmap_tags %>の位置を動かしてみる?
補足情報(FW/ツールのバージョンなど)
Rails 7.0.4
Ruby 3.0.4p208
VSCode

回答1件
あなたの回答
tips
プレビュー