Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Rails partial with data from action cable

I try to build a chat page with action cable. I successfully get the new message data like

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) {
  }
});

Here I have data as a JavaScript object. I need to render a rails partial (with many ruby logic inside)

- 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

But I cannot pass a JS data object as locals to render this partial. I though about 2 options, sending an ajax request to send data to the server or create a new html template (with many logic) inside the javascript. Both seems complicated. Anyone can suggest a better method?

like image 911
Ian Tran Avatar asked Dec 14 '22 17:12

Ian Tran


1 Answers

You can send an html template and js variables in two separate properties of the json response:

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
like image 51
golfadas Avatar answered Dec 28 '22 05:12

golfadas