Is there a way to broadcast from the controller instead of the model (Rails)

I am trying to create a chat app and would like the messages to be styled differently depending on who’s chatroom is being viewed.

In order to do that I need my _message.html.erb partial to be able to see what chat room is being viewed so I have a hidden_field_tag :room_id, in my new message form.

The problem is that I’m having trouble finding a way to pass the room_id as a local variable to my _messagepartial because I can't pass the params to themessage.rb` model.

I’m wondering if there is a way to call the turbo stream broadcast from the controller action so I can pass the the param[:room_id]?

Using the Hotwire demo app as an example, you could adapt something like:

# messages_controller.rb
# def create …
@viewed_room = Room.find(params[:room_id])
Turbo::StreamsChannel.broadcast_append_to @room, target: 'messages', partial: 'messages/message', locals: { message: @message, viewed_room: @viewed_room }

(and remove broadcasts_to… from the Message model)

1 Like

Thank you, after trying your solution out I realized I can just do


within my controller action

Ah nice! I failed to spot that the broadcast_* methods are both class and instance methods.