Basically, I am trying to get saves to the database to be broadcasted to all streamers.
I know that the websocket stream is working because when I call App.call.speak() from the client, the received() function is triggered and I see an alert.
I know that the after_create() method on the model is working because the second function prints to the console.
The broadcast function (ActionCable.server.broadcast()) is being called from the model but simply is not working as it does from the chat_channel.rb
I want to call it from the model.
chat.coffee
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
update: I figured it out. See answer.
I was trying to broadcast by creating records in rails console. Thats what didnt work. When I used an ajax request, everything worked as expected.