Action Cable lets your Rails app send and receive live updates instantly without refreshing the page.
Action Cable for real-time updates in Ruby on Rails
class ChatChannel < ApplicationCable::Channel def subscribed stream_from "chat_channel" end def unsubscribed # Any cleanup needed when channel is unsubscribed end def speak(data) ActionCable.server.broadcast "chat_channel", message: data['message'] end end
stream_from sets the channel to listen for broadcasts.
Methods like speak handle data sent from clients.
class NotificationsChannel < ApplicationCable::Channel def subscribed stream_from "notifications_#{current_user.id}" end end
def speak(data) ActionCable.server.broadcast "chat_channel", message: data['message'] end
This example shows a simple chat channel in Rails and how the client connects and sends messages. When a message is sent, all connected clients receive it instantly.
class ChatChannel < ApplicationCable::Channel def subscribed stream_from "chat_channel" end def speak(data) ActionCable.server.broadcast "chat_channel", message: data['message'] end end // Client-side JavaScript example (using Rails default setup): // app/javascript/channels/chat_channel.js import consumer from "./consumer" consumer.subscriptions.create("ChatChannel", { connected() { console.log("Connected to ChatChannel") }, received(data) { console.log("New message:", data.message) }, speak(message) { this.perform('speak', { message: message }) } }) // Usage in browser console: // consumer.subscriptions.subscriptions[0].speak('Hello everyone!')
Remember to run bin/rails server and have Redis running for Action Cable to work smoothly.
Use stream_from carefully to avoid sending too much data to clients.
Test real-time features in multiple browser tabs to see live updates.
Action Cable adds live, real-time features to Rails apps easily.
It uses channels to send and receive messages instantly.
Clients subscribe to channels and get updates without page reloads.
Practice
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 AQuick Check:
Real-time updates = To add real-time features allowing live updates without page reloads [OK]
- Confusing Action Cable with background job tools
- Thinking it manages database tasks
- Assuming it styles the app
Solution
Step 1: Recall Action Cable subscription syntax
The correct method to subscribe to a channel is usingsubscriptions.create.Step 2: Match options with correct method
Only App.cable.subscriptions.create('ChatChannel') usessubscriptions.create('ChatChannel'), which is the correct syntax.Final Answer:
App.cable.subscriptions.create('ChatChannel') -> Option AQuick Check:
Subscription method = subscriptions.create [OK]
- Using subscribe instead of subscriptions.create
- Using connect or open which are invalid methods
- Missing quotes around channel name
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from 'chat_room'
end
endAnd this JavaScript subscription:
App.cable.subscriptions.create('ChatChannel', {
received(data) {
console.log(data.message)
}
})What will happen when the server broadcasts
{ message: 'Hello!' } to 'chat_room'?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 BQuick Check:
Broadcast to stream triggers received callback = The message 'Hello!' will be logged in the browser console [OK]
- Confusing channel name with stream name
- Expecting alert instead of console log
- Thinking server errors without perform method
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from notifications
end
endSolution
Step 1: Check the stream_from argument type
The argument tostream_frommust be a string representing the stream name, e.g., 'notifications'.Step 2: Identify the error in the code
The code usesnotificationswithout quotes, treating it as a variable, which causes an error.Final Answer:
The stream_from argument should be a string, not a variable -> Option CQuick Check:
stream_from needs string argument [OK]
- Forgetting quotes around stream name
- Inheriting from wrong class
- Assuming stream_from is deprecated
Solution
Step 1: Identify the correct broadcast method
To send a message to all subscribers of a stream, useActionCable.server.broadcast(stream, data).Step 2: Analyze options for correct usage
ActionCable.server.broadcast('notifications', { comment: @comment.body }) usesActionCable.server.broadcastwith stream name and data hash, which is correct.Final Answer:
ActionCable.server.broadcast('notifications', { comment: @comment.body }) -> Option DQuick Check:
Broadcast to stream uses ActionCable.server.broadcast [OK]
- Using broadcast_to without a model instance
- Calling broadcast on ActionCable directly
- Passing data without wrapping in a hash
Ready to prove it?
Pass the test and this pattern moves unknown
