0

I build a chat using ActionCable. I want the messages to have a different styling wether I or any other User has written them.
Mainly my own messages should be displayes on the right side and the messages from other users should be displayed left.

Here's the issue. When I submit a message, it is displayed with the wrong styling (wrong site) for the other users. A pagerefresh fixes this until a new message is broadcasted.

Is there a way to fix this?

message_partial

- if current_user == msg.user
  .message.me
    .message-body
        %span.message-username= link_to msg.user.name, msg.user, target: '_blank'
        %time
            %i.icon-clock
            = msg.created_at.strftime('%H:%M:%S')

        = raw(msg.content_html)
    = link_to image_tag(msg.user.avatar.url(:extrasmall), alt: msg.user.name, class: "user-img"), msg.user, target: '_blank'
-  else
  .message.other
    = link_to image_tag(msg.user.avatar.url(:extrasmall), alt: msg.user.name, class: "user-img"), msg.user, target: '_blank'
    .message-body
        %span.message-username= link_to msg.user.name, msg.user, target: '_blank'
        %time
            %i.icon-clock
            = msg.created_at.strftime('%H:%M:%S')

        = raw(msg.content_html)

chatroom_partial

App.proom = App.cable.subscriptions.create "ProomChannel",
connected: ->

disconnected: ->

received: (data) ->
    unless data.msg.blank?
        $('#messages-table').append data.msg
        scroll_bottom()
        play_sound()


$(document).on 'turbolinks:load', ->
  submit_msg()
  scroll_bottom()


submit_msg = () ->
  $('#msg_content').on 'keydown', (event) ->
    if event.keyCode is 13
        $('#msg_button').click()
        event.target.value = ""
        event.preventDefault()

scroll_bottom = () ->
  try
    $('.chat').scrollTop($('.chat')[0].scrollHeight)
  catch
Max
  • 275
  • 1
  • 4
  • 21

1 Answers1

1

Probably the best way is to add another attribute to the message, like "who", fill it before broadcasting (current_user == msg.user ? 'me' : 'other') and then use it to decide where to append the message.

something like:

if (data.who == 'me') {
  $('.message.me').append data.msg
}
m3characters
  • 2,240
  • 2
  • 14
  • 18