如何在rails控制器中调用通道方法?

gwa*_*ton 10 ruby ruby-on-rails ruby-on-rails-3 actioncable

我有一个订阅用户的ActionCable方法.如果启动了新的convo,我也想要将用户订阅到新频道.我无法弄清楚在控制器中调用通道方法的正确语法.

更新:问题是消息在发送时被附加到聊天框,但是当第一条消息被发送时,websocket连接尚未建立,因此它向用户查看消息是否未被发送(因为它是没有附加).

信道/ msgs_channel.rb

class MsgsChannel < ApplicationCable::Channel  
  #This function subscribes the user to all existing convos
  def subscribed
    @convos = Convo.where("sender_id = ? OR recipient_id = ?", current_user, current_user)
    @convos.each do |convo|
        stream_from "msg_channel_#{convo.id}"
    end
  end

  #This is a new function I wrote to subscribe the user to a new convo that is started during their session.
  def subscribe(convo_id)
      stream_from "msg_channel_#{convo_id}"
  end
end
Run Code Online (Sandbox Code Playgroud)

在我的convos控制器中,创建方法,我尝试了几件事:

convos_controller.rb

def create
  @convo = Convo.create!({sender_id: @sender_id, recipient_id: @recipient_id})
  ActionCable.server.subscribe(@convo.id)
end
Run Code Online (Sandbox Code Playgroud)

ActionCable.subscribe(@convo.id)

错误: NoMethodError (undefined method订阅'for ActionCable:Module)`


ActionCable.msgs.subscribe(@convo.id)

错误: NoMethodError (undefined method对于ActionCable:模块的msgs':`


  App.msgs.subscribe(@convo.id)
Run Code Online (Sandbox Code Playgroud)

错误:NameError (uninitialized constant ConvosController::App):


MsgsChannel.subscribe(@convo.id)

错误:NoMethodError (undefined method订阅'for MsgsChannel:Class`


ActionCable.server.subscribe(@convo.id)

错误:NoMethodError (undefined method订阅'#):`

Tal*_*aul 1

因此,您不应该在创建时将用户订阅到控制器中的频道。它应该基于他们访问该页面的时间。您应该通过添加 js/coffe 文件来更改用户的连接位置,以便根据连接的人员为您执行此操作。当我学习时,一个很好的例子/教程是这里的这个视频。

视频遗漏的是如何连接到个人对话。所以我苦苦挣扎,找到了一种从 url 中获取对话 id 的方法,可能不是最好的方法,但它有效。希望这可以帮助

conversation_id = parseInt(document.URL.match(new RegExp("conversations/"+ "(.*)"))[1]) # gets the conversation id from the url of the page

App.conversation = App.cable.subscriptions.create { channel: "ConversationChannel", conversation_id: conversation_id },
  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
Run Code Online (Sandbox Code Playgroud)