【问题标题】:Rails actioncable transmits wrong stylingRails actioncable 传输错误的样式
【发布时间】:2017-06-25 20:50:50
【问题描述】:

我使用 ActionCable 建立聊天。我希望消息具有不同的样式,无论是我还是任何其他用户编写的。
主要是我自己的消息应该显示在右侧,其他用户的消息应该显示在左侧。

这就是问题所在。当我提交消息时,它会以错误的样式(错误的站点)显示给其他用户。在广播新消息之前,页面刷新会修复此问题。

有没有办法解决这个问题?

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 actioncable


    【解决方案1】:

    可能最好的方法是在消息中添加另一个属性,例如“谁”,在广播之前填充它(current_user == msg.user ?'me':'other'),然后使用它来决定在哪里附加消息。

    类似:

    if (data.who == 'me') {
      $('.message.me').append data.msg
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 2016-11-30
      • 2023-03-22
      • 2017-10-13
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      相关资源
      最近更新 更多