Search code examples
ruby-on-railsruby-on-rails-5actioncable

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


The descriptions here seem to imply that stream_for is used only when passing in a record, but overall the documentation is rather vague. Can anyone explain the differences between stream_from and stream_for and why would you use one over the other?


Solution

  • 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