Immediate Communication with Action Cable

Learn about immediate communication with Action Cable.

Let’s look at an example of using Action Cable to broadcast sold-out concert data to our schedule page. We’ll need to write some code server-side and some code client-side. On the server-side, we need to create a channel and also set up the place where data is sent to that channel. On the client-side, we need to respond to data when it’s sent.

We’ve set up this functionality to be the most basic Action Cable as possible—the data only flows one way from the server to the client, and the identical broadcast goes to all subscribers. The schedule is the same for everybody.

Generating boilerplate

We can start by asking Rails to generate some boilerplate:

% rails generate channel ScheduleChannel

This will generate two files: a server-side file app/channels/schedule_channel.rb and a client-side file app/javascripts/channels/schedule_channel.js.

If this is your first Action Cable Rails generation, Rails will also create an index.js file for app/javascripts/channels. Like the similar file created for Stimulus controllers, this will automatically load any file in that directory ending in _channel.js.

Rails will also create a file at app/javascripts/consumer.js, which frankly, is an odd little shortcut for calling the Action Cable method createConsumer. It will make more sense in a minute when I talk about our client-side code. We are going to ignore these boilerplate files and integrate Action Cable ourselves.


First, we need to define the channel on the server-side. The channel does not do very much here:

Get hands-on with 1200+ tech skills courses.