You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/guides/rails.md
+35-32Lines changed: 35 additions & 32 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -477,7 +477,37 @@ With this approach:
477
477
478
478
## Streaming Responses with Hotwire/Turbo
479
479
480
-
The default persistence flow is designed to work seamlessly with streaming and Turbo Streams for real-time UI updates. Here's a simplified approach using a background job:
480
+
The default persistence flow is designed to work seamlessly with streaming and Turbo Streams for real-time UI updates.
481
+
482
+
### Basic Pattern: Instant User Messages
483
+
484
+
For a better user experience, show user messages immediately while processing AI responses in the background:
485
+
486
+
```ruby
487
+
# app/controllers/messages_controller.rb
488
+
classMessagesController < ApplicationController
489
+
defcreate
490
+
@chat=Chat.find(params[:chat_id])
491
+
492
+
# Create and persist the user message immediately
493
+
@chat.create_user_message(params[:content])
494
+
495
+
# Process AI response in background
496
+
ChatStreamJob.perform_later(@chat.id)
497
+
498
+
respond_to do |format|
499
+
format.turbo_stream { head :ok }
500
+
format.html { redirect_to @chat }
501
+
end
502
+
end
503
+
end
504
+
```
505
+
506
+
The `create_user_message` method handles message persistence and returns the created message record. This pattern provides instant feedback to users while the AI processes their request.
507
+
508
+
### Complete Streaming Setup
509
+
510
+
Here's a full implementation with background job streaming:
481
511
482
512
```ruby
483
513
# app/models/chat.rb
@@ -503,9 +533,11 @@ end
503
533
classChatStreamJob < ApplicationJob
504
534
queue_as :default
505
535
506
-
defperform(chat_id, user_content)
536
+
defperform(chat_id)
507
537
chat =Chat.find(chat_id)
508
-
chat.ask(user_content) do |chunk|
538
+
539
+
# Process the latest user message
540
+
chat.complete do |chunk|
509
541
# Get the assistant message record (created before streaming starts)
510
542
assistant_message = chat.messages.last
511
543
if chunk.content && assistant_message
@@ -544,35 +576,6 @@ end
544
576
<% end %>
545
577
```
546
578
547
-
### Controller Integration
548
-
549
-
Putting it all together in a controller:
550
-
551
-
```ruby
552
-
# app/controllers/messages_controller.rb
553
-
classMessagesController < ApplicationController
554
-
before_action :set_chat
555
-
556
-
defcreate
557
-
message_content = params[:content]
558
-
559
-
# Queue the background job to handle the streaming response
0 commit comments