我有一个ActionCable的方法,用于订阅用户。如果开始了新的对话,我也想要订阅用户到新的频道。我无法弄清楚在控制器中调用通道方法的正确语法。
更新:问题在于当发送消息时将消息附加到聊天框中,但当发送第一条消息时,websocket连接尚未建立,因此对用户来说看起来好像消息未发送(因为消息没有附加)。
channel/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_controller」的「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)
错误信息:
NoMethodError (undefined method
subscribe' for ActionCable:Module)`
ActionCable.msgs.subscribe(@convo.id)
错误信息:
NoMethodError (undefined method
msgs' for ActionCable:Module):`
App.msgs.subscribe(@convo.id)
错误:NameError(未初始化的常量ConvosController :: App):
MsgsChannel.subscribe(@convo.id)
错误:NoMethodError(undefined method subscribe' for MsgsChannel:Class`
ActionCable.server.subscribe(@convo.id)
错误:NoMethodError(undefined method subscribe' for#):`