Rails Turbo Broadcast Update to Partial
How to send page updates with [Hotwire](https://hotwire.dev) using a specific partial.
How to send page updates with Hotwire using a specific partial.
The Views
When broadcasting, the rendering engine expects a partial to render. This is nice anyway because you can use the partial in the rendered HTML page. By default it uses the partial for the model doing the broadcast. But it's easily overridden.
Setup the main view with turbo_stream_from
and render the partial that will be changed by the broadcast in a container with an id, verification_status
.
/ show.html.slim
section.container.mx-auto.p-4.mb-8
= turbo_stream_from @profile
#verification_status
== render 'verify_id', profile: @profile
/ _status.html.slim
/ SUCCEED Verification
- if profile.result == RESULTS.succeed
p
| That worked!
/ FAILED Verification
- if profile.result == RESULTS.failed
p
| Oops that failed :(
The Broadcast
Now, from a background job, response to a webhook, or where ever; you can broadcast the update.
profile.broadcast_action :update, target: "verification_status", partial: "profile/status"
Make sure to include Turbo::Broadcastable
in the model.
class Profile < ApplicationRecord
include Turbo::Broadcastable
# ...
end
Tests
To make sure whatever should broadcast is broadcasting you can use ActionCable::TestHelper
and Turbo::Streams::StreamName
.
class Hooks::ProfileController < ActionDispatch::IntegrationTest
include ActionCable::TestHelper
include Turbo::Streams::StreamName
test "should handle callback" do
profile = create(:profile)
assert_broadcasts stream_name_from(profile), 1 do
get "/hooks/profile/callback/#{profile.id}?result=succeed"
end
assert_response :success
end
end
Webmentions
These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: