为什么actioncable允许我从我的chat_channel.rb进行广播,而不允许从我的模型文件(chat.rb)



基本上,我正在尝试将保存到数据库中的内容广播到所有流媒体。

我知道websocket流正在工作,因为当我从客户端调用App.call.speak()时,received()函数会被触发,我会看到一个警报。

我知道模型上的after_create()方法正在工作,因为第二个函数打印到控制台。

广播函数(ActionCable.server.broadcast())是从模型中调用的,但它根本无法像从chat_channel.rb 中那样工作

我想根据模型来命名它。

聊天室咖啡

App.chat = App.cable.subscriptions.create "ChatChannel",
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) ->
alert("hi")
speak: (message) ->
@perform 'speak', message: message

chat_channel.rb

class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(message)
ActionCable.server.broadcast 'chat', message: "hello"
end
end

models/message.rb

class Message < ApplicationRecord
belongs_to :user
after_create :broadcast, :print_out
def print_out
puts "print after create"
end
def broadcast
ActionCable.server.broadcast 'chat', message: "hello"  
end
end

更新:我想明白了。请参阅答案。

我试图通过在rails控制台中创建记录来进行广播。这就是不起作用的地方。当我使用ajax请求时,一切都按预期进行。

最新更新