0

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??

Tolga
  • 1,307
  • 3
  • 16
  • 31

2 Answers2

2

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
DmitryBash
  • 48
  • 3
2

Declare the variable in your subscribed method. Think of the subscribed method as an initializer in the context of your channel.

An example exists within the ActionCable codebase itself. In your case, this can be achieved like so

class ProductChannel < ApplicationCable::Channel
  def subscribed
    @product = Product.find(params[:product_id])
    stream_from "room_channel_product_#{@product.id}"
  end

  def unsubscribed
  end

  def foo
    @product.do_stuff
  end
end
theterminalguy
  • 1,842
  • 18
  • 20