【问题标题】:Rails Turbo-Stream update my div won't workRails Turbo-Stream 更新我的 div 不起作用
【发布时间】:2022-07-19 18:33:06
【问题描述】:

我正在尝试更新页面中的 div。

<div id="post_hidden_fields"></div>

我将控制器添加到 turbo_stream 格式代码中以更新此 div

respond_to do |format|      
            format.turbo_stream do
                render turbo_stream: turbo_stream.update("post_hidden_fields", 
                partial: "home/update_post_form", locals: {post_type: params[:post_type], url: params[:url]})
            end
            format.html {} 
        end

我的 home/update_post_form 部分看起来像这样:

<div id="post_hidden_fields">
<input autocomplete="off" type="hidden" name='<%= "post[#{post_type}]" %>' value="<%= url %>">

当它运行时,我查看我的网络选项卡,对该方法的响应是:

<turbo-stream action="update" target="post_hidden_fields">
<template>
    <div id="post_hidden_fields">
        <input autocomplete="off" type="hidden" name='post[photo]' value="SOME_URL">
    </div>
</template>

似乎 turbo-stream 部分运行正常,但不知何故 dom 不会改变。我仍然让我的 post_hidden_​​fields div 为空,并且没有保留我试图添加到其中的隐藏输入。

【问题讨论】:

  • 您不应该使用turbo_stream.update,因为您要替换整个元素而不仅仅是更新其内容,因此您应该使用turbo_stream.replace

标签: ruby-on-rails ruby hotwire-rails


【解决方案1】:
  1. 为您的输入创建一个部分并将您的输入添加到 turbo_stream 标记中

     <%= turbo_frame_tag :custom_form do %>
        # add your partial here partial here
        <%= render partial: "partial_path", locals: { ... } %>
     <% end %>
    
  2. 现在针对您的操作创建一个文件,例如 action.turbo_stream.erb

  3. 在您的 action.turbo_stream.erb 中,使用唯一名称调用您的 turbo_frame_tag,在我的例子中是 custom_form,并用新值替换您的部分

      <%= turbo_stream.replace : custom_form do %>
        # replacing the partial with turbo
        <%= render partial: 'partial_path', locals: { ... } %>
      <% end %>
    

您的所有 DOM 元素都将使用 turbo_stream 重新渲染。

【讨论】:

  • 谢谢。我做了类似的事情,并且在我的日志中确实得到了“Rendering home/set_new_image.turbo_stream.erb”。但在我的控制台中,我不断收到“Uncaught SyntaxError: Unexpected token '
【解决方案2】:

您需要使用“替换”而不是“更新” 例子:-

render turbo_stream: turbo_stream.replace("post_hidden_fields", partial: "home/update_post_form", locals: {post_type: params[:post_type], url: params[:url]})

【讨论】:

    猜你喜欢
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2015-10-30
    • 2015-10-24
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多