top of page

Broadcasting with dependencies in Rails

  • RFilo CTO
  • 15 de abr.
  • 1 min de leitura

Atualizado: 23 de jul.


Broadcasting with dependencies in Rails

Broadcasting with dependencies in Rails updates easily with broadcast_replace_to, broadcast_append_to, etc.

But what if you need to scope the broadcast to the current_user? That’s where dependency injection using Current comes in handy.

Let’s say we want to update a post in real-time only for the current user. You can do that from inside the model like this:


class Post < ApplicationRecord
	after_update_commit -> { broadcast_replace_to [current_user, self] }

	private
	def current_user
		Current.user
	end
end

This tells Rails to create a unique stream for a combination of current_user and the post instance.

On the client side (in your Turbo Streams or views), make sure the stream tag matches this scope:

<%= turbo_stream_from [current_user, post] %>

⚠️ Important: You need to assign Current.user manually — for example, in a controller or job:

class PostsController < ApplicationController
	before_action :set_current_user
	def update
		@post.update(post_params)
	end
	
	private
	def set_current_user
		Current.user = current_user
	end
end

Using Current keeps your models clean and aware of the request context without passing user objects around explicitly.

Clean. Scoped. Real-time. 🚀


Comments


rails-rtoledo_edited.png

Hi, I'm Rodrigo Toledo

A full-stack developer skilled in both front-end and back-end development, building and maintaining web applications

  • Facebook
  • Youtube
  • LinkedIn
  • Instagram

I don't know everything, help me

I'm always seeking to improve what I build and to refine my skills. Whenever I master something, I share it. And when I don't understand, I dive deep until I do—learning, growing, and helping others along the way.

Subscribe

Thanks for submitting!

bottom of page