As far as I know, you cannot do this directly with JavaScript without channels (Redis needs to be translated first).
I suggest you do it like a regular post action, and then send a message to Rails.
I would do something like this:
JavaScript:
$.ajax({type: "POST", url: "/notifications", data: {notification: {message: "Hello world"}}})
Controller:
class NotificationsController < ApplicationController def create ActionCable.server.broadcast( "notifications_channel", message: params[:notification][:message] ) end end
A source:
class NotificationsChannel < ApplicationCable::Channel def subscribed stream_from("notifications_channel", coder: ActiveSupport::JSON) do |data| # data => {message: "Hello world"} transmit data end end end
Listen to JavaScript:
App.cable.subscriptions.create( {channel: "NotificationsChannel"}, { received: function(json) { console.log("Received notification: " + JSON.stringify(json)) } } )
source share