Action Cable lets your Rails app send and receive live updates instantly without refreshing the page.
0
0
Action Cable for real-time updates in Ruby on Rails
Introduction
You want chat messages to appear instantly for all users.
You need live notifications when new data arrives.
You want to update a dashboard in real-time as data changes.
You want multiplayer game moves to show immediately to all players.
You want to show live comments or likes without page reload.
Syntax
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.
Examples
This streams notifications only for the current user by using their ID.
Ruby on Rails
class NotificationsChannel < ApplicationCable::Channel def subscribed stream_from "notifications_#{current_user.id}" end end
This method broadcasts the received message to all subscribed clients.
Ruby on Rails
def speak(data) ActionCable.server.broadcast "chat_channel", message: data['message'] end
Sample Program
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.
Ruby on Rails
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!')
OutputSuccess
Important Notes
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.
Summary
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.