📖 Scenario: You are building a simple chat feature for a website. Users should see new messages appear instantly without refreshing the page.
🎯 Goal: Create a basic Action Cable setup in Rails that broadcasts new chat messages to all connected users in real-time.
📋 What You'll Learn
Create a channel for chat messages
Set up a subscription to the chat channel in JavaScript
Broadcast new messages from the Rails server
Display incoming messages instantly on the webpage
💡 Why This Matters
🌍 Real World
Real-time chat and notifications are common in social media, customer support, and collaboration tools.
💼 Career
Understanding Action Cable helps you build interactive Rails apps that respond instantly to user actions, a valuable skill for web developers.
Progress0 / 4 steps
1
Create the ChatChannel
Create a new channel file called app/channels/chat_channel.rb with a class ChatChannel that inherits from ApplicationCable::Channel. Inside it, define a subscribed method that streams from "chat_channel".
Ruby on Rails
Hint
Use stream_from inside the subscribed method to listen to the channel named "chat_channel".
2
Subscribe to ChatChannel in JavaScript
In app/javascript/channels/chat_channel.js, create a subscription to "chat_channel" using createConsumer().subscriptions.create. Add a received function that appends the received message to an element with id "messages".
Ruby on Rails
Hint
Use subscriptions.create("ChatChannel", { received(data) { ... } }) to handle incoming messages.
3
Broadcast messages from Rails
In your MessagesController, after saving a new message, broadcast it to "chat_channel" using ActionCable.server.broadcast with a hash containing the key :message and the message text.
Ruby on Rails
Hint
Use ActionCable.server.broadcast("chat_channel", message: @message.content) to send the new message to all subscribers.
4
Add messages container in HTML
In your chat view file (e.g., app/views/messages/index.html.erb), add a <div> with id "messages" where incoming messages will appear.
Ruby on Rails
Hint
Add a container with id="messages" so JavaScript can add new messages inside it.
Practice
(1/5)
1. What is the main purpose of Action Cable in a Rails application?
easy
A. To add real-time features allowing live updates without page reloads
B. To manage database migrations automatically
C. To handle background jobs and scheduling
D. To style the application with CSS frameworks
Solution
Step 1: Understand Action Cable's role
Action Cable integrates WebSockets into Rails to enable live, real-time communication.
Step 2: Compare options with Action Cable's purpose
Only To add real-time features allowing live updates without page reloads describes real-time updates without page reloads, which is what Action Cable does.
Final Answer:
To add real-time features allowing live updates without page reloads -> Option A
Quick Check:
Real-time updates = To add real-time features allowing live updates without page reloads [OK]
Hint: Remember: Action Cable = live updates without refreshing [OK]
Common Mistakes:
Confusing Action Cable with background job tools
Thinking it manages database tasks
Assuming it styles the app
2. Which of the following is the correct way to create a channel subscription in a Rails JavaScript client using Action Cable?
easy
A. App.cable.subscriptions.create('ChatChannel')
B. App.cable.subscribe('ChatChannel')
C. App.cable.connect('ChatChannel')
D. App.cable.open('ChatChannel')
Solution
Step 1: Recall Action Cable subscription syntax
The correct method to subscribe to a channel is using subscriptions.create.
Step 2: Match options with correct method
Only App.cable.subscriptions.create('ChatChannel') uses subscriptions.create('ChatChannel'), which is the correct syntax.
Final Answer:
App.cable.subscriptions.create('ChatChannel') -> Option A
Quick Check:
Subscription method = subscriptions.create [OK]
Hint: Use subscriptions.create to subscribe to channels [OK]
Common Mistakes:
Using subscribe instead of subscriptions.create
Using connect or open which are invalid methods
Missing quotes around channel name
3. Given this channel code in Rails:
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from 'chat_room'
end
end
What will happen when the server broadcasts { message: 'Hello!' } to 'chat_room'?
medium
A. Nothing will happen because the channel name is incorrect
B. The message 'Hello!' will be logged in the browser console
C. The message will be displayed as an alert popup
D. The server will throw an error due to missing perform method
Solution
Step 1: Understand the channel subscription and streaming
The channel streams from 'chat_room', and the client subscribes to 'ChatChannel' with a received callback logging data.message.
Step 2: Analyze the broadcast effect
When the server broadcasts { message: 'Hello!' } to 'chat_room', the client receives it and logs 'Hello!' to the console.
Final Answer:
The message 'Hello!' will be logged in the browser console -> Option B
Quick Check:
Broadcast to stream triggers received callback = The message 'Hello!' will be logged in the browser console [OK]
Hint: Broadcast to stream triggers received callback logging message [OK]
Common Mistakes:
Confusing channel name with stream name
Expecting alert instead of console log
Thinking server errors without perform method
4. Identify the error in this Action Cable channel code:
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from notifications
end
end
medium
A. The channel class should inherit from ApplicationController
B. The subscribed method is missing a call to reject unauthorized users
C. The stream_from argument should be a string, not a variable
D. The stream_from method is deprecated and should not be used
Solution
Step 1: Check the stream_from argument type
The argument to stream_from must be a string representing the stream name, e.g., 'notifications'.
Step 2: Identify the error in the code
The code uses notifications without quotes, treating it as a variable, which causes an error.
Final Answer:
The stream_from argument should be a string, not a variable -> Option C
Quick Check:
stream_from needs string argument [OK]
Hint: Always quote stream names in stream_from method [OK]
Common Mistakes:
Forgetting quotes around stream name
Inheriting from wrong class
Assuming stream_from is deprecated
5. You want to broadcast a message to all users subscribed to 'notifications' channel whenever a new comment is created. Which code snippet correctly achieves this in Rails?
hard
A. ActionCable.broadcast('notifications', @comment.body)
B. NotificationsChannel.broadcast_to('notifications', { comment: @comment.body })
C. broadcast_to('notifications', { comment: @comment.body })
D. ActionCable.server.broadcast('notifications', { comment: @comment.body })
Solution
Step 1: Identify the correct broadcast method
To send a message to all subscribers of a stream, use ActionCable.server.broadcast(stream, data).
Step 2: Analyze options for correct usage
ActionCable.server.broadcast('notifications', { comment: @comment.body }) uses ActionCable.server.broadcast with stream name and data hash, which is correct.
Final Answer:
ActionCable.server.broadcast('notifications', { comment: @comment.body }) -> Option D
Quick Check:
Broadcast to stream uses ActionCable.server.broadcast [OK]
Hint: Use ActionCable.server.broadcast to send to all subscribers [OK]
Common Mistakes:
Using broadcast_to without a model instance
Calling broadcast on ActionCable directly
Passing data without wrapping in a hash
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.