假设我有一个用Rails Form Builder构建的表单.它有一个文本字段,我想使用AJAX和turbo流动态更新输入字段的值.

是否可以从turbo流视图中使用text_field助手更新相同文本字段的值,而不用新创建的文本字段替换它?

这个Gorails tutorial有类似的用例,但他正在更新一个SELECT标记的值.因此,他使用options_for_select帮助程序更新了SELECT标记的选项,以便 Select 字段保留在DOM上,而只有选项被替换.

推荐答案

没有内置的方法可以做到这一点,但制作定制的turbo流操作非常容易:

// app/javascript/application.js

Turbo.StreamActions.update_input = function () {
  this.targetElements.forEach((target) => {
    target.value = this.templateContent.textContent
  });
};
# app/views/users/_form.html.erb

<%= form_with model: @user do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %> 
# app/controllers/users_controller.rb

def update
  helpers.fields model: @user do |f|
    render turbo_stream: turbo_stream.action(
     :update_input, f.field_id(:name), "new value"
    )
  end
end

100

If you need another example:
https://stackoverflow.com/a/76112894/207090

Ruby-on-rails相关问答推荐

为什么这个rails Collection_select不呈现关联属性?

Rails Heroku部署:预编译assets资源 失败.SassC::语法错误

Trailblazor 操作 -> 集合 :attribute(has_many 通过关联) 与填充器 -> 如何填充 Reform::Form 形式的 slugs 数组?

为什么在使用 Ruby on Rails 时我的徽标没有出现在 Bootstrap 导航栏中?

我需要在我的 Rails 7 应用程序中保留 app/assets/config/manifest.js 吗?

Rails:has_many 通过不返回结果

Rails 7 共享刺激控制器功能

如何使用 activerecord activerecord-session_store 在 Rails 应用程序中使用 cookie 值在数据库中查找会话记录

Rails:关于yields

Rails - 生产模式下的错误

Ruby on Rails 错误无法加载此类文件 - 更少

如何在 Rails ActiveRecord 中指定日期小于今天的条件

Rails 范围为 IS NOT NULL 并且不为空/空白?

在rails国际化yml文件中传递变量

用于在多行上链接调用的 Ruby 约定

rake 任务中的 def 块

Ruby 1.87 与 1.92 Date.parse

Rails 3:乘客找不到Bundle 程序安装的 git gem

如何测试也定义为辅助方法的 ApplicationController 方法?

是否可以输出rake db:migrate产生的 SQL 更改脚本?