Rails Action Cable #
一、Action Cable概述 #
1.1 创建频道 #
bash
rails generate channel Chat
1.2 频道定义 #
ruby
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{params[:room]}"
end
def speak(data)
ActionCable.server.broadcast "chat_#{params[:room]}", message: data['message']
end
end
二、客户端连接 #
2.1 JavaScript连接 #
javascript
const chat = consumer.subscriptions.create("ChatChannel", {
received(data) {
console.log(data.message)
}
})
chat.speak({ message: 'Hello' })
三、总结 #
3.1 核心要点 #
| 要点 | 说明 |
|---|---|
| Channel | 频道 |
| stream_from | 订阅流 |
| broadcast | 广播消息 |
3.2 下一步 #
现在你已经掌握了Action Cable,接下来让我们学习 缓存机制,深入了解Rails的缓存系统!
最后更新:2026-03-28