如何在Rails 7中默认将请求设置为TURBO_STREAM
1. 全局配置form_with默认格式
form_with的默认参数可以通过初始化文件全局设置,不用每次调用都手动加format: :turbo_stream:
在config/initializers目录下新建turbo_defaults.rb文件,写入以下代码:
# config/initializers/turbo_defaults.rb ActionView::Helpers::FormHelper.default_form_with_options = { format: :turbo_stream }
之后所有form_with生成的表单,默认都会以TURBO_STREAM格式发送请求。
2. 全局设置link_to和button_to默认启用Turbo Stream
link_to和button_to默认不会自动带Turbo Stream标识,我们可以重写ApplicationHelper里的这两个方法,全局添加data-turbo-stream="true"属性:
打开app/helpers/application_helper.rb,添加以下代码:
# app/helpers/application_helper.rb module ApplicationHelper def link_to(name = nil, options = nil, html_options = nil, &block) html_options ||= {} html_options[:data] ||= {} # 全局开启Turbo Stream,个别需要关闭的可手动传data: { turbo_stream: false } html_options[:data][:turbo_stream] = true unless html_options[:data].key?(:turbo_stream) super(name, options, html_options, &block) end def button_to(name = nil, options = nil, html_options = nil, &block) html_options ||= {} html_options[:data] ||= {} html_options[:data][:turbo_stream] = true unless html_options[:data].key?(:turbo_stream) super(name, options, html_options, &block) end end
这段代码会给所有link_to和button_to自动加上Turbo Stream的data属性,要是有个别链接不需要用Turbo Stream,调用时手动传入data: { turbo_stream: false }就能覆盖全局设置。
3. 确保控制器能响应Turbo Stream请求
最后要保证控制器动作能处理Turbo Stream格式的响应。Rails 7默认已经集成Turbo,只要你在对应视图目录下创建了[action_name].turbo_stream.erb模板,控制器就会自动渲染对应的Turbo Stream响应。
比如你有PostsController的create动作,只要在app/views/posts/下创建create.turbo_stream.erb,里面写Turbo Stream操作代码(比如<%= turbo_stream.append :posts, @post %>),就能正常处理请求。
内容的提问来源于stack exchange,提问作者Yash

