What is the difference between `stream_from` and `stream_for` in ActionCable?

stream_for is simply a wrapper method of stream_from with ease.

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

Let's assume you have a chat_room instance of ChatRoom class,

stream_from "chat_rooms:#{chat_room.to_gid_param}"

or

stream_for chat_room # equivalent with stream_from "chat_rooms:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE"

the two lines of code does the same thing.

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


kevinhyunilkim's answer is almost ok, but prefix depends on channel_name, not 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 simple string to stream_for which simply adds channel name.