带条件显示的动作有线聊天

时间:2019-05-03 00:44:46

标签: ruby-on-rails

我正在寻找使用动作电缆构建聊天应用程序。我遵循了本教程:enter link description here

我已经构建了该应用程序的基础,并且可以从控制台发送消息,并且消息可以在多台PC的右div中显示。 我想实现两件事:

  1. 能够从表单(而不是从控制台)进行书写 show.html.erb
  2. 能够基于user_id更改CSS(如果 current_user == user_id)。这个问题与我 无法将current_user传递给工作,因此需要欺骗一些东西。

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 %>

0 个答案:

没有答案