Rails 5 ActionCable 从 URL 参数建立流 [英] Rails 5 ActionCable establish stream from URL parameters
问题描述
我对 Rails 几乎完全陌生,或者我相信我自己会知道如何回答这个问题.我只是想修改在基本 ActionCable 演示中创建的基本聊天应用程序:https://medium.com/@dhh/rails-5-action-cable-demo-8bba4ccfc55e#.6lmd6tfi7
I am almost completely new to Rails, or I am sure I would know how to answer this question myself. I am just trying to modify the basic chat app created in the basic ActionCable demo: https://medium.com/@dhh/rails-5-action-cable-demo-8bba4ccfc55e#.6lmd6tfi7
我想拥有多个聊天室,而不是只有一个聊天室,所以我修改了我的 routes.rb
,添加了这一行:
Instead of having just one chat room, I want to have multiple chat rooms, so I modified my routes.rb
by adding this line:
get '/rooms/show/:topic', to: 'rooms#show'
所以现在我可以根据不同的主题访问不同的聊天室./app/controllers/rooms_controller.rb
中的房间控制器可以毫无问题地处理这些路由:
So now I can visit different chat rooms based on different topics. The rooms controller at /app/controllers/rooms_controller.rb
handles these routes with no problem:
class RoomsController < ApplicationController
def show
@topic = params[:topic]
@messages = Message.all
end
end
但是这个参数没有被传递到 app/channels/room_channel.rb
,我只是不确定我需要做哪些修改.我目前的尝试:
But this parameter is not being passed to app/channels/room_channel.rb
, and I'm just not sure what modifications I need to make. My current attempt:
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel_#{params[:topic]}"
end
只返回room_channel_"
only returns "room_channel_"
推荐答案
这里的问题是我无法理解从哪里调用订阅的方法,因此不知道如何将参数传递给它.
The problem here was that I failed to understand from where the subscribed method was being called, and thus did not know how to pass parameters to it.
通过阅读 actioncable 文档:https://github.com/rails/rails/tree/master/actioncable
By reading the actioncable documentation: https://github.com/rails/rails/tree/master/actioncable
我发现订阅的方法是通过客户端 javascript 调用的,而不是通过 rails 控制器调用的.在示例聊天应用程序的情况下,这意味着我必须更改文件 /app/assets/javascripts/channels/room.coffee
I found out that the subscribed method is called via client-side javascript, not by the rails controller. In the case of the example chat app, this means I had to change the first line of the file /app/assets/javascripts/channels/room.coffee
App.room = App.cable.subscriptions.create "RoomChannel",
到
App.room = App.cable.subscriptions.create { channel: "RoomChannel", topic: topic},
将 javascript 对象传递给此方法允许我在 rooms_controller.rb
的 subscribed
方法中访问这些参数.
Passing a javascript object to this method allowed me to access those parameters in the subscribed
method of rooms_controller.rb
.
这篇关于Rails 5 ActionCable 从 URL 参数建立流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!