Rails 5 ActionCable sets a stream from URL parameters

I'm almost completely new to Rails, or I'm sure I know how to answer this question myself. I'm just trying to change the main chat application created in the main ActionCable demo: https://medium.com/@dhh/rails-5-action-cable-demo-8bba4ccfc55e#.6lmd6tfi7

Instead of having only one chat, I want to have several chats, so I changed my routes.rb by adding this line:

get '/rooms/show/:topic', to: 'rooms#show'

So now I can attend different chats based on different topics. The room controller in /app/controllers/rooms_controller.rb can handle these routes without problems:

 class RoomsController < ApplicationController def show @topic = params[:topic] @messages = Message.all end end 

But this parameter is not passed to app/channels/room_channel.rb , and I just donโ€™t know what changes I need to make. My current attempt:

 class RoomChannel < ApplicationCable::Channel def subscribed stream_from "room_channel_#{params[:topic]}" end 

returns "room_channel _"

+4
source share
2 answers

The problem was that I did not understand where the signed method was called from, and therefore did not know how to pass parameters to it.

After reading the actioncable documentation: https://github.com/rails/rails/tree/master/actioncable

I found out that the signed method is being called through client javascript and not using the rails controller. In the case of the chat application example, this means I had to change the first line of the /app/assets/javascripts/channels/room.coffee file

 App.room = App.cable.subscriptions.create "RoomChannel", 

to

 App.room = App.cable.subscriptions.create { channel: "RoomChannel", topic: topic}, 

Passing a javascript object to this method allowed me to access these parameters in the subscribed rooms_controller.rb method.

+10
source

Set topic_id to the HTML tag, possibly in the body tag in your layout file.

 <body data-topic-id="<%= @topic.id %>"> 

Now read it from JS as follows:

 document.querySelector('body').dataset.topicId 

The line for creating your subscription will look like this:

 App.room = App.cable.subscriptions.create (channel: 'RoomChannel', topic_id: document.querySelector('body').dataset.topicId) 
+1
source

Source: https://habr.com/ru/post/1247701/


All Articles