現在、action cableを用いたRails のチャット機能を実装しております。
具体的にはログインしているuser 同士が1対1でチャットができる機能です。
createaアクションがうまく実装できておらず、ビュー上でメッセージを入力しても、
登録ができない状況です、
下記のコードの問題点をご指摘いただけますと大変幸いです。
schema.rb(
1 2create_table "chat_messages", force: :cascade do |t| 3 t.string "message", null: false 4 t.datetime "created_at", null: false 5 t.datetime "updated_at", null: false 6 t.integer "user_id" 7 t.integer "chat_room_id" 8 t.index ["chat_room_id"], name: "index_chat_messages_on_chat_room_id" 9 t.index ["user_id"], name: "index_chat_messages_on_user_id" 10 end 11 12 create_table "chat_rooms", force: :cascade do |t| 13 t.datetime "created_at", null: false 14 t.datetime "updated_at", null: false 15 t.integer "user_id" 16 t.index ["user_id"], name: "index_chat_rooms_on_user_id" 17 end 18
chat_controller
1class ChatController < ApplicationController 2 before_action :authenticate_user! 3 4 def index 5 @chat_rooms = ChatRoom.all 6 end 7 8 def show 9 10 #@user == user(current_user) 11 @chat_room = ChatRoom.find_by(params[:id]) 12 13 @chat_message = ChatMessage.new 14 @chat_messages = ChatMessage.all 15 16 end 17 18 19 def create 20 @chat_room = ChatRoom.new 21 if @chat_message.save 22 redirect_to chat_index_path 23 else 24 redirect_to root_path 25 end 26 end 27 28 29end 30
chat_room.rb
1class ChatRoom < ApplicationRecord 2 has_many :chat_messages,dependent: :destroy 3end 4
chat_messeage.rb
1class ChatMessage < ApplicationRecord 2 belongs_to :chat_room 3 belongs_to :user 4end 5
chat/show.html.erb
1<h1>チャットサンプル</h1> 2<% if user_signed_in? %> 3 <h3>チャットルーム</h3> 4 <div class="chat-field"> 5 6 7 </div> 8 9 <%else %> 10 </div> 11<% end %> 12 13<div class="container"> 14 15 <h1><%= "Chat Room #{@chat_room.id}" %></h1> 16 <h4 class="border"><%= "Your Mail Address: #{current_user&.email}" %></h4> 17 <div id="messages", data-room_id="<%= @chat_room.id %>"> 18 <%= render @chat_messages %> 19 </div> 20 <div class="input"> 21 <form> 22 <label>post</label> 23 <input type="text" data-behavior="room_speaker"> 24 </form> 25 </div> 26</div> 27 28<%= form_with model: @chat do |f| %> 29 <%= f.text_field :messeage %> 30 <%= f.submit "メッセージを送る"%> 31<% end %> 32 33 <%= link_to "<<back index", chat_index_path %>
恐れ入りますが、何卒宜しくお願い致します。
あなたの回答
tips
プレビュー