@h2_hero_hh (h2_hero_hh)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

エラー unknown attribute 'text' for Comment.

解決したいこと

・チャット投稿機能実装
ActionCableを用いて、リアルタイムチャットアプリを作成したいのですが、下記のエラーが発生しております。

勉強し始めて、1ヶ月ともあり、みなさまのご指導をいただきたいです。
よろしくお願いいたします。

発生している問題・エラー

ea423584a5b48f6c2463c2eda016979b.png

該当するソースコード

app/controllers/homeromms_controller.rb

class HomeroomsController < ApplicationController

  def index
    @comments = Comment.all
    @teachers = Teacher.all
  end

  def create
    @comment = Comment.new(text: params[:comment])
    if @comment.save
      ActionCable.server.broadcast 'comment_channel', content: @comment
    end
  end

  private

  def comment_params
    params.permit(:comment).merge(student_id: current_student.id)
  end

end

app/views/homeromms/index.html.erb

<div class="main-container">
  <div class="container">
    <div class="comments_lists">
      <% @comments.each do |comment| %>
        <div class="message-date">
          <%= l comment.created_at %>
        </div>
        <div class="message-comment">
          <%= comment.comment %>
        </div>
      <% end %>
    </div>
  </div>
</div>

app/models/comment.rb

class Comment < ApplicationRecord
  belongs_to :student
end

app/javascript/comment_channel.js

import consumer from "./consumer"

consumer.subscriptions.create("CommentChannel", {
  connected() {
  },

  disconnected() {
  },

  received(data) {
    const html = `<p>${data.content.comment}</p>`;
    const comments = document.getElementById('comments');
    const newComment = document.getElementById('comment_text');
    comments.insertAdjacentHTML('afterbegin', html);
    newComment.value='';
    }
});

自分で試したこと

・カラム名の記述が間違えているか※こちらの記事を調べました(https://qiita.com/Ayaka_ramens/items/f0c68b08fcf6145c2b17)

0 likes

1Answer

カラム名を調べるにはその記事の方法ではなく、 rails c でコンソールを起動して Comment.column_names を実行してください。

> Comment.column_names
=> ["id",
 "text",
  略]

のように "text" が入っていれば正常ですが、そのエラーからすると入っていないと思います。なければ text カラムを追加するマイグレーションを実行する必要があります。

rails g migration AddTextToComments text:string でマイグレーションファイルを作り、 rails db:migrate でマイグレーションを実行してください。

1Like

Comments

  1. @h2_hero_hh

    Questioner

    ありがとうございます。
    エラー解決しましたが、コメント投稿が出来ず、リロードを行っても反映されないのですが、ひとまず調べてみます!

Your answer might help someone💌