Is it possible to specify the location of a turbo_stream.erb template?

Scenario

Take for example the following code:

class AwesomeController < ApplicationController
  
  ...
  
  def update
    respond_to do |format|
      format.html
      format.turbo_stream
    end
  end
  
  ...
  
end

As I understand it, the default behavior of format.turbo_stream is render a *.turbo_stream.erb file with the same name of the action, in the associated views subdirectory.

So in this case, the following file would be rendered: app/views/awesome/update.turbo_stream.erb.

Question

I want to specify a different file, in a different location (e.g., app/views/somewhere_else/update.turbo_stream.erb).
Is this possible?

Self-Help

  • Where can I find the documentation on format.turbo_stream?
  • I’m also particularly interested in reading about the turbo_stream option for render (e.g., render turbo_stream: turbo_stream.update(...). Where can I find this documentation?

I haven’t actually tried this with turbo streams, so take it with a grain of salt, but the automatic rendering from the controller that Rails does is a convention that can be overridden. Here’s the section in the guides describing how you render a different template from a controller action. I would assume this is possible with turbo streams too since Rails is inferring the file path from convention here too. You could possibly wrap the render method in a conditional based on format.

Thanks for the response.

I did try specifying a different path but Rails doesn’t recognize the template. Here’s the error I get:

Missing template somewhere_else/update with {:locale=>[:en], :formats=>[:turbo_stream], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :haml, :jbuilder]}

I can verify that the template is there.

Here’s the code:

respond_to do |format|
  if @some_model.update(some_model_params)
    format.turbo_stream do
      render "somewhere_else/update"
    end
  end
end

One solution could be update the extension from update.turbo_stream.erb to just a regular template update.html.erb so the code looks like:

respond_to do |format|
  if @some_model.update(some_model_params)
    render "somewhere_else/update", content_type: Mime[:turbo_stream]
  end
end