You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7中如何将Stimulus请求格式从*/*改为turbo_stream?

实现方法

1. 修改Stimulus控制器的Fetch请求

注意:你的Stimulus控制器文件名应该是toggle_controller.js(对应视图里的data-controller="toggle"),如果当前文件名不符请先调整。

在connect方法中给fetch请求添加Accept请求头,明确告知服务器需要Turbo Stream格式的响应:

static targets = ["txt"]
static values = { url: String }

connect() {
  // this.hideBtnTarget.hidden = true  // 注意:当前代码中未定义hideBtnTarget,若不需要可删除
  console.log(this.urlValue);
  fetch(this.urlValue, {
    headers: {
      // 指定接受Turbo Stream格式
      'Accept': 'text/vnd.turbo-stream.html'
    }
  }).then((success) => {
    console.log(success);
  }).catch((e) => {
    console.log(e);
  })
}

copy(){
  let txt = this.txtTarget
  txt.select()
  document.execCommand("copy")
  txt.value = ""
}

2. 让Rails控制器返回Turbo Stream响应

有两种方式实现:

方式一:创建Turbo Stream模板

在app/views/stimulus/目录下创建index.turbo_stream.erb文件,编写Turbo流操作逻辑,例如:

<%= turbo_stream.update 'some-target-id', partial: 'shared/updated_content' %>

方式二:在控制器动作中直接渲染

如果不需要单独模板,可直接在stimulus_controller.rb的index方法中写:

def index
  render turbo_stream: turbo_stream.update('some-target-id', html: '<p>内容已通过Turbo Stream更新</p>')
end

3. 可选:直接在URL中指定格式

如果不想修改请求头,也可以在视图传递URL时直接指定格式:

<div data-controller="toggle" data-toggle-url-value="<%= root_path(format: :turbo_stream) %>">
<div>
       <p class="mt-5">Copy text content</p>
       <input type="text" data-toggle-target="txt"/>
       <button data-action="click->toggle#copy">Copy</button>
</div>

这种方式会让请求URL自动带上.turbo_stream后缀,Rails会自动识别并返回对应格式的响应。

内容的提问来源于stack exchange,提问作者Rahul Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:01:13