使用动作电缆中的数据部分渲染Rails

时间:2018-03-20 09:34:12

标签: ruby-on-rails actioncable

我尝试使用动作电缆构建聊天页面。我成功地获得了像

这样的新消息数据
App.room = App.cable.subscriptions.create({
  channel:  "API::V1::TransactionMessageChannel",
  transaction_id: gon.transaction_id
}, {
  connected: function() {},
  disconnected: function() {},
  received: function(data) {
    alert(data["user"]["full_name"]);
  },
  appendLine: function(data) {
    var html = createLine(data)
    $(".chat-area ul").append(html)
  },
  createLine: function(data) {
  }
});

这里我将数据作为JavaScript对象。我需要渲染一个部分轨道(里面有许多ruby逻辑)

- if @current_user['id'] == data['user']['id']
  li.left.clearfix.admin-chat
    span.chat-img1.pull-right
      img.img-circle alt=data['user']['full_name'] src=display_avatar(data['user']['avatar_url'])
    .chat-content.me.clearfix
      - case data['transaction_message']['activity']
      - when 'attach_image'
        p
          a.img data-fancybox="gallery" href=data['transaction_message']['message']
            img src=data['transaction_message']['message'] style="height:130px;"
      - when 'attach_file'
            p
              a target="_blank" href=data['transaction_message']['message']
                i.fa.fa-file-text-o
                '
                = data['transaction_message']['message'].split('/').last
      - else
        p = data['transaction_message']['message']
        .chat-time.pull-left
          = timeago_tag Time.at(data['transaction_message']['created_at']), lang: I18n.locale

但我无法将JS数据对象作为本地传递来呈现此部分。我虽然有两个选项,发送ajax请求发送数据到服务器或在javascript内创建一个新的html模板(有很多逻辑)。两者似乎很复杂。任何人都可以提出更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以在json响应的两个单独属性中发送html模板和js变量:

class ChatChannel < ApplicationCable::Channel
  def speak(data)
    ActionCable.server.broadcast('messages',
      html: html(data),
      variables: { foo: :bar }
    )
  end

  def html(message)
    ApplicationController.render(
      partial: 'messages/message',
      locals: { message: message }
    )
  end
end