rails5.2、Action Cableにて簡易なチャットアプリを作っております。
下記などを参考にしました。
Action Cableでリアルタイムチャットアプリの作成方法 (Rails 5.1.4にて)(その1) herokuで動かす!
アプリ自体は動作しているのですが、通信相手と想定して別タブで確認すると、文字の部分にundefinedと出力されてしまいます。
※F5すると文字は表示されます
JavaScript(chat.js)が原因かなと思うのですが分かりません。
ブラウザ、サーバともにエラーログは出ていません。
分かる方教えていただけないでしょうか?
どうぞ宜しくお願いします。
/app/views/messages/in_progress.html.erb
ruby
1 2 <ul id="chat-index"> 3 <% @messages.each do |m| %> 4 <li><%= m.text %></li> 5 <% end %> 6 </ul> 7 8 9 <form> 10 <input id="chat-form" type="text" data-behavior="chat_post" name="message" value="" > 11 </form> 12 13
/app/assets/javascripts/channels/chat.js
javascript
1/* global $*/ 2App.chat = App.cable.subscriptions.create("ChatChannel", { 3 4 connected: function() {}, 5 disconnected: function() {}, 6 received: function(data) { 7 return $('#chat-index').append('<p>' + data['message'] + '</p>'); 8 }, 9 10 post: function(message) { 11 return this.perform('post', { message: message }); 12 } 13}, 14$(document).on('keypress', '[data-behavior~=chat_post]', function(event) { 15 if (event.keyCode === 13) { 16 var chatForm = $('#chat-form'); 17 App.chat.post(chatForm.val()); 18 return chatForm.val(''); 19 } 20})); 21 22
/app/channels/chat_channel.rb
ruby
1class ChatChannel < ApplicationCable::Channel 2 def subscribed 3 stream_from "chat_channel" 4 end 5 6 def unsubscribed 7 # Any cleanup needed when channel is unsubscribed 8 end 9 10 def post(data) 11 #ActionCable.server.broadcast('chat_channel', data) 12 Message.create! text: data['message'] 13 end 14end 15
/app/models/message.rb
ruby
1class Message < ApplicationRecord 2 after_create_commit { MessageBroadcastJob.perform_later self } 3end 4
/app/jobs/message_broadcast_job.rb
ruby
1class MessageBroadcastJob < ApplicationJob 2 def perform(message) 3 ActionCable.server.broadcast('chat_channel', message) 4 end 5 6 private 7 def render_message(message) 8 ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message }) 9 end 10end 11
/app/controllers/messages_controller.rb
ruby
1class MessagesController < ApplicationController 2 3 def in_progress 4 @messages = Message.all 5 end 6 7end 8
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/07/15 03:42