我正在寻找使用动作电缆构建聊天应用程序。我遵循了本教程:enter link description here。
我已经构建了该应用程序的基础,并且可以从控制台发送消息,并且消息可以在多台PC的右div中显示。 我想实现两件事:
Chatroom.coffee
App.chatroom = App.cable.subscriptions.create "ChatroomChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
$('#messages').append data['message']
speak: (message) ->
@perform 'speak', message: message
$(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
if event.keyCode is 13 # return = send
App.room.speak event.target.value
event.target.value = ''
event.preventDefault()
Chatmessage_broadcast_job.rb
class ChatmessageBroadcastJob < ApplicationJob
queue_as :default
def perform(message, current_user_id)
current_user = User.find(current_user_id)
ActionCable.server.broadcast 'chatroom_channel', message: render_message(message),message: message, user: current_user
end
private
def render_message(message)
ApplicationController.renderer.render(partial: 'chatmessages/message', locals: { message: message })
end
end
Chatroom_channel.rb
class ChatroomChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
stream_from "chatroom_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(data)
Chatmessage.create! content: data['message'], user: current_user
end
end
show.html.erb
<div class="section_event" style="margin-left: 0px; text-align: left !important;">
<%= t :Live_chat %> </div>
<form>
<label> Say something: </label>
<input type="textarea" data-behavior="room_speaker" class="form-control">
</form>
<div id="messages">
</div>
这是在 _message.html.erb
中创建问题编号2 ...的条件<% if current_user.id == message.user_id %>
<div class="chatmessage_sent">
<div><strong><%= User.find_by(id: message.user_id).full_name %></strong></div>
<div><%= message.content %></div>
</div>
<% else %>
<div class="chatmessage_received">
<div><strong><%= User.find_by(id: message.user_id).full_name %></strong></div>
<div><%= message.content %></div>
</div>
<% end %>