I would like to create chatrooms per product page so that uses can chat about the product while they are isolated from other products' discussions.
For this purpose; I was planning to use @product instance varialbe while defining the subscriptions however it seems; instance variables are not accessible within Action Cable
"app/channels/product_channel.rb"
class ProductChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel_product_#{@product.id}"
end
def unsubscribed
end
end
How can I access instance variables within channel module??
I think you can't access the instance variable while defining the subscriptions. But you can pass product_id as a parameter, then you subscribe to the ProductChannel. https://guides.rubyonrails.org/action_cable_overview.html#subscriber
App.cable.subscriptions.create { channel: "ProductChannel", product_id: your_product_id }
And on your channel, you can access to "product_id" like:
def subscribed
stream_from "product_channel_#{params[:product_id]}"
end