Rails javascript部分没有得到更新记录

Rails javascript partial is not getting updated record

本文关键字:更新 新记录 javascript Rails      更新时间:2023-09-26

我有这样的视图:

<!-- Loads custom Stylesheet -->
<%= stylesheet_link_tag 'simulation' %>
<!-- Loads polling calls to update -->
<script type="text/javascript">
    <%= render 'show.js.erb' %>
</script>
<!-- Render simulation -->
<%= render 'simulation' %>
<%= link_to 'Back', simulations_path %>

包含以下两个偏导:

_show.js.erb:

callUpdate = function(id) {
    if (id) {
        console.log("tic")
        $.ajax({
            type: "PUT",
            url: "/simulations/" + id
        });
    } else {
        console.log("Update error, no id passed.")
    }
    $('#sim_div').html("<%= j (render @simulation) %>");
    setTimeout( function() {
        callUpdate(id)
    }, 5000);
};
setTimeout( function() {
    callUpdate("<%= @simulation.id %>")
}, 5000);

_simulation.html.erb:

<div id="sim_div">
  <h1><%= @simulation.identifier %></h1>
  <h4 class="offset-col-sm-1">Dimensions: <%= @simulation.x_size %>x<%= @simulation.y_size %></h4>
  <h4 class="offset-col-sm-1">Verdict: <%= @simulation.verdict %></h4>
  <!-- REMOVE -->
 <h1> <%= @simulation.dirty? %></h1>
  <table class="table table-bordered">
    <thead>
      <tr>
      </tr>
    </thead>
    <tbody>
      <% @simulation.state.each_with_index do |row, y_index| %>
        <tr>
        <% row.each_with_index do |current, x_index| %>        
            <td class="text-center <%= 'dirty' if @simulation.dirty_points.include?([x_index,y_index]) %>"><%= current %></td>        
          <% end%>
        </tr>
      <% end %>
    </tbody>
  </table>
  <br>
</div>

javascript正在调用我的控制器更新函数,它在更新函数上设置脏记录。

simulation_controller #显示:

def update
    @simulation = Simulation.find(params[:id])
    @simulation.next # <= THIS SETS DIRTY RECORDS ON THE OBJECT
    @simulation.save
    respond_to do |format|
        format.js
        format.html { redirect_to simulations_url }
    end
end

我的javascript代码从来没有从更新调用后得到新的更新记录,我想让它,当他们不再更新调用停止调用更新和停止轮询。然而,它只能看到初始记录,这不是脏的。只有_simulation部分似乎接收到新的记录(即使它是由javascript代码重新渲染,所以我不知道为什么javascript不能看到更新的记录。)

我如何访问更新记录的属性,而不仅仅是javascript代码中的原始属性?谢谢!

您的callUpdate javascript函数实际上可能每5秒执行一次,但它一遍又一遍地呈现相同的@simulation(初始化的)而没有更改。你的javascript部分只被渲染一次(初始视图),它会发出无尽的ajax请求,没完没了地用相同的内容一遍又一遍地替换某些元素的html。

相反,您应该在这些ajax调用的每个响应上更新某些元素的内部html。

从初始视图中取出这一行:

$('#sim_div').html("<%= j (render @simulation) %>");

并将其移动到更新操作的响应模板中(可能是:update.js.erb)