我有一个订阅用户的 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
在我的 convos 控制器的 create 方法中,我尝试了几件事:
convos_controller.rb
def create
@convo = Convo.create!({sender_id: @sender_id, recipient_id: @recipient_id})
ActionCable.server.subscribe(@convo.id)
end
ActionCable.subscribe(@convo.id)
error:
NoMethodError (undefined method
订阅 ActionCable:Module)`
ActionCable.msgs.subscribe(@convo.id)
error:
NoMethodError (undefined method
ActionCable 的消息:模块):`
App.msgs.subscribe(@convo.id)
error:NameError (uninitialized constant ConvosController::App):
MsgsChannel.subscribe(@convo.id)
error:NoMethodError (undefined method
订阅 MsgsChannel:Class`
ActionCable.server.subscribe(@convo.id)
error:NoMethodError (undefined method
订阅#):`