0

前提

RailsとJavaScriptでメモアプリを作っています。
複数のメモを同時に投稿したいため、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

Rails.application.routes.draw do

  root 'notes#index'
  get 'notes/new' => 'notes#new'
  post 'notes/create' => 'notes#create'

end

notes_controller.rb

class NotesController < ApplicationController

  def index
    @notes = Note.all
  end

  def new
  end

  def create
    params[:notes].each do |text|
      @note = Note.new(text: text)
      @note.save
    end
    redirect_to("/")
  end

end

application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>MemoApp</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <%= link_to "index", "/" %>
    <%= link_to "new", "/notes/new" %>
    <%= yield %>
  </body>
</html>

new.html.erb

<form>
  <input type="text" id="note-value">
  <button type="submit" id="note-submit">追加</button>
</form>

<form id="note-list" action="/notes/create" method="post">
  <button type="submit">作成</button>
</form>

app/javascript/custom/script.js

const noteValue = document.getElementById('note-value');
const noteSubmit = document.getElementById('note-submit');
const noteList = document.getElementById('note-list');

noteSubmit.addEventListener('click', e => {
  e.preventDefault();
  const text = noteValue.value;
  if(text) {
    const note = `<input type="text" value=${text} name="notes[]"></input>`;
    noteList.insertAdjacentHTML('afterbegin', note);
    noteValue.value = "";
  }
});

参考サイト/【JavaScriptの実践】TODOリストの作り方

JavaScript読み込み用に追加したコード

app/javascript/application.js

import "./custom/script.js"

config/importmap.rb

pin_all_from "app/javascript/custom", under: "custom"

参考サイト/Rails 7でJavaScriptファイルを読み込みたい

試したこと

jsをwindow.addEventListener('DOMContentLoaded', => {})で囲ってみる?
application.html.erbの<%= javascript_importmap_tags %>の位置を動かしてみる?

補足情報

Rails 7.0.4
Ruby 3.0.4p208
VSCode

1
  • Rails 7 とのことですが、turbolinks は利用されていますでしょうか?
    – nekketsuuu
    2022年10月29日 5:28

0

この質問に回答するには、ログインする必要があります。