我已经提到了headers a few次recently次,所以我将这一部分保持简短:
当您发送TURBO_STREAM请求时,优先的第一个格式是turbo_stream
.如果没有turbo_stream格式块或turbo_stream.erb模板,则使用html
格式.因为turbo可以处理这两个响应,所以它设置Accept
标头来确定要运行哪个格式块.你可以从destroy
行动中看一看:
puts request.headers["Accept"]
#=> text/vnd.turbo-stream.html, text/html, application/xhtml+xml
# ^ ^
# turbo is first in line html is second
def destroy
@model.destroy
respond_to do |format|
format.turbo_stream { render turbo_stream: turbo_stream.remove(@model) }
format.html { redirect_to models_url, notice: "Destroyed." }
end
end
To get a turbo_stream response
<%= link_to "Turbo destroy", model_path(model),
data: {turbo_method: :delete}
%>
To get an html response
Rails还可以忽略Accept
报头并根据URL扩展来确定格式.呼叫/models/1.html
的涡轮增压请求将以html回应.
<%= link_to "HTML turbo destroy", model_path(model, format: :html),
data: {turbo_method: :delete}
%>
<%= button_to "HTML turbo destroy", model_path(model, format: :html),
method: :delete
%>
我最不喜欢的turbo: false
个选项,讨厌:
<%= button_to "HTML rails destroy", model_path(model),
method: :delete,
data: {turbo: false}
%>
Use url/form params to do whatever you want
<%= button_to "Turbo destroy with params", model_path(model),
method: :delete,
params: {redirect_to: "/anywhere/you/like"} # or maybe just true/false
%>
def destroy
@model.destroy
respond_to do |format|
# just pass a param and disable the turbo_stream block
unless params[:redirect_to]
format.turbo_stream { render turbo_stream: turbo_stream.remove(@model) }
end
format.html { redirect_to (params[:redirect_to] || models_url), notice: "Destroyed." }
end
end
如果这仍然不能解决问题,您可以发送您自己的fetch
个请求,并且只为您需要的格式设置一个Accept
头.请参阅顶部的链接.