Broadcasting with dependencies in Rails
- RFilo CTO
- há 1 minuto
- 1 min de leitura
Rails makes broadcasting updates easy 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. 🚀
#RubyOnRails #Hotwire #TurboStreams #RailsBroadcasting #RealTimeRails #WebDev #CodingTips #Rails7 #StimulusReflex #FullstackRuby #RubyTips
Posts recentes
Ver tudoWhen working with parameters in Rails applications, especially nested ones, developers often face challenges like NoMethodError ...
What is the N+1 Query Problem? The N+1 query problem occurs when an application performs excessive database queries due to inefficient...