Skip to content

Commit

Permalink
Broadcast
Browse files Browse the repository at this point in the history
  • Loading branch information
takeyuweb committed Feb 23, 2022
1 parent f73c72a commit 21c8695
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 5 deletions.
3 changes: 3 additions & 0 deletions app/controllers/messages_controller.rb
Expand Up @@ -8,6 +8,9 @@ def create
@message = Message.new(params.require(:message).permit(:body))
respond_to do |format|
if @message.save
# Broadcast to the "messages_channel" channel (asynchronous)
@message.broadcast_prepend_later_to("messages_channel")

format.html { redirect_to messages_url }
format.turbo_stream
else
Expand Down
4 changes: 4 additions & 0 deletions app/models/message.rb
@@ -1,3 +1,7 @@
class Message < ApplicationRecord
validates :body, presence: true
# To broadcast in a model callback, write the following
# after_create_commit -> { broadcast_prepend_to("messages_channel", partial: "messages/message") } # Specify a partial template
# after_create_commit -> { broadcast_prepend_later_to("messages_channel") } # Broadcast asynchronously using ActiveJob.
# after_create_commit -> { broadcast_prepend_to("messages_channel") }
end
4 changes: 0 additions & 4 deletions app/views/messages/create.turbo_stream.erb
Expand Up @@ -3,7 +3,3 @@
<%= render partial: "form", locals: { form: form } %>
<% end %>
<% end %>
<%= turbo_stream.prepend "messages" do %>
<%= render @message %>
<% end %>
3 changes: 2 additions & 1 deletion app/views/messages/index.html.erb
Expand Up @@ -13,4 +13,5 @@
</div>
</div>

<%#= turbo_stream_from "messages" %>
<%#= Subscribe to the "messages_channel" channel %>
<%= turbo_stream_from "messages_channel" %>

0 comments on commit 21c8695

Please sign in to comment.