How To Fix Actioncontroller::unknown Format When Using Turbo Stream With Rails And Turbo
When you follow the hotrails's turbo stream tutorial you get the impression that the following should work.
Inside index.html.erb
file:
<%= link_to "Edit", edit_quote_path(quote) %>
Inside quotes controller:
def edit
respond_to do |format|
format.turbo_stream
end
end
When you open the page and click on the Edit link what happens is that you get the following error: ActionController::UnknownFormat
.
I had to dig a bit deeper to realise that this message is shown depending on what you send under the Accept
header. In general that's controller by Rails, and by default for the Edit link above the default Accept
header is text/html, application/xhtml+xml
.
However, in the quotes controller the only format edit
responds to is turbo_stream
, not text/html
.
Turbo stream requires Accept
header to be text/vnd.turbo-stream.html
.
So if our controller only reponds to format turbo_stream
, we need to instruct Rails to accept text/vnd.turbo-stream.html
.
Rails is going to use this instruction to respond with a turbo_stream
.
Therefore, to fix the ActionController::UnknownFormat
error, index.html.erb
should be changed to:
<%= link_to "Edit", edit_quote_path(quote), data: { turbo_stream: true } %>
With this instruction the Accept
header becomes text/vnd.turbo-stream.html, text/html, application/xhtml+xml
which means that Rails is now instructed to accept turbo_stream
and pass it as a valid format to the caller.