What is the right place to broadcast from?

Does it vary from case to case?

I’ve seen:

model broadcasts

class Post < ApplicationRecord
  broadcasts_to ->(post) { :posts }

  # or
  after_create_commit do
    broadcast_update_to :posts, target: 'posts_count', partial: "posts/count", locals: { count: Post.count  }
  end
end

controller broadcasts

class CountersController < ApplicationController
  def increment
    @counter.increment

    respond_to do |format|
      format.turbo_stream do
         render turbo_stream: turbo_stream.update(@counter),
                              partial: 'counters/counter_value',
                              locals: { counter: @counter }
      end
    end
  end
end

or

format.turbo_stream with separate views similar to the old format.scriptnew.js.erb

<%= turbo_stream.update @counter, "counters/counter" locals: {counter: @counter} %>

Your second option is just an inline Turbo stream, you are not broadcasting.
But in my case I broadcast from a method in ApplicationController, then a bit higher level than controllers associated to models. Also it is sent to Sidekiq.

def stream_resume(resume)
  Turbo::StreamsChannel.broadcast_replace_later_to(
        resume,
        partial: "resumes/resume_as_string", locals: {resume: resume},
        target: "display_resume"
      )
end
1 Like

Assuming you meant broadcasting, I’ll just add my thoughts on where the broadcast. I’ve avoided putting broadcasts in my callbacks because I’ve found it to make it unclear what side affects updating/creating/destroying a record has. My application might be a bit more complex but I’ve opted to stay away from callbacks and put them in controller responses or in service objects / interactors.

Hope this helps!

1 Like