What is the difference between stream_from and stream_for in ActionCable?

The descriptions here imply that stream_for is only used when passing to records, but in general the documentation is pretty vague. Can someone explain the differences between stream_from and stream_for and why will you use one over the other?

+6
source share
2 answers

stream_for is just a stream_from wrapper stream_from with ease.

When you need a stream related to a specific model, stream_for automatically generates a broadcast from the model and channel for you.

Suppose you have a chat_room instance of the chat_room class,

 stream_from "chat_rooms:#{chat_room.to_gid_param}" 

or

 stream_for chat_room # equivalent with stream_from "chat_rooms:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE" 

two lines of code do the same.

https://github.com/rails/rails/blob/master/actioncable/lib/action_cable/channel/streams.rb

+8
source

kevinhyunilkim's answer is almost normal, but the prefix depends on the channel name and not on the model class.

 class CommentsChannel < ApplicationCable::Channel def subscribed stream_for article # is equivalent to stream_from "#{self.channel_name}:{article.to_gid_param}" # in this class this means stream_from "comments:{article.to_gid_param}" end private # any activerecord instance has 'to_gid_param' def article Article.find_by(id: params[:article_id]) end end 

you can also pass a simple string to stream_for , which simply adds the channel name.

0
source

All Articles