简体   繁体   中英

Rails Action Cable: How can I access instance variables within ApplicationCable::Channel Class?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM