Turbo Stream Not Updating View After CSV Upload – Need to Refresh the Page Manually

I’m working on a Rails 8.0 app that uses Turbo Streams to dynamically update certain sections of the page after uploading a CSV file. However, after I upload the CSV and process the data, the page does not automatically update with the new content. I have to manually refresh the page to see the changes.

Here’s what I have so far:

Code in the Controller (ProductsController):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class ProductsController < ApplicationController
require 'csv'
def index
@csv_data = session[:csv_data] || [] # Load uploaded CSV data from session
end
def import
if params[:file].present?
csv_file = params[:file]
@csv_data = []
CSV.foreach(csv_file.path, headers: true) do |row|
relevant_data = {
"sku_code" => row["sku_code"],
"product_id" => row["product_id"],
"product_title" => row["product_title"],
"sell_price" => row["sell_price"],
"tax_rate" => row["tax_rate"],
"suppliers" => parse_supplier_data(row)
}
@csv_data << relevant_data
end
session[:csv_data] = @csv_data
respond_to do |format|
format.turbo_stream { render turbo_stream: [
turbo_stream.replace("products_table", partial: "products_table", locals: { csv_data: @csv_data }),
turbo_stream.replace("action_buttons", partial: "action_buttons")
]}
format.html { redirect_to products_path, notice: "CSV uploaded and parsed successfully." }
end
else
redirect_to products_path, alert: "Please upload a valid CSV file."
end
rescue StandardError => e
Rails.logger.error "Error processing CSV: #{e.message}"
redirect_to products_path, alert: "Error processing CSV: #{e.message}"
end
def clear
session[:csv_data] = nil # Clear the CSV data stored in the session
redirect_to products_path, notice: "Data cleared. You can upload a new CSV."
end
private
def parse_supplier_data(row)
suppliers = []
supplier_columns = row.headers.select { |col| col.match?(/supplier_d+_/) }
supplier_ids = supplier_columns.map { |col| col[/supplier_(d+)_/, 1] }.uniq
supplier_ids.each do |supplier_id|
suppliers << {
"supplier_id" => row["supplier_#{supplier_id}_id"],
"supplier_name" => row["supplier_#{supplier_id}_name"],
"supplier_cost" => row["supplier_#{supplier_id}_cost"],
"supplier_ref" => row["supplier_#{supplier_id}_ref"]
}
end
suppliers
end
end
</code>
<code>class ProductsController < ApplicationController require 'csv' def index @csv_data = session[:csv_data] || [] # Load uploaded CSV data from session end def import if params[:file].present? csv_file = params[:file] @csv_data = [] CSV.foreach(csv_file.path, headers: true) do |row| relevant_data = { "sku_code" => row["sku_code"], "product_id" => row["product_id"], "product_title" => row["product_title"], "sell_price" => row["sell_price"], "tax_rate" => row["tax_rate"], "suppliers" => parse_supplier_data(row) } @csv_data << relevant_data end session[:csv_data] = @csv_data respond_to do |format| format.turbo_stream { render turbo_stream: [ turbo_stream.replace("products_table", partial: "products_table", locals: { csv_data: @csv_data }), turbo_stream.replace("action_buttons", partial: "action_buttons") ]} format.html { redirect_to products_path, notice: "CSV uploaded and parsed successfully." } end else redirect_to products_path, alert: "Please upload a valid CSV file." end rescue StandardError => e Rails.logger.error "Error processing CSV: #{e.message}" redirect_to products_path, alert: "Error processing CSV: #{e.message}" end def clear session[:csv_data] = nil # Clear the CSV data stored in the session redirect_to products_path, notice: "Data cleared. You can upload a new CSV." end private def parse_supplier_data(row) suppliers = [] supplier_columns = row.headers.select { |col| col.match?(/supplier_d+_/) } supplier_ids = supplier_columns.map { |col| col[/supplier_(d+)_/, 1] }.uniq supplier_ids.each do |supplier_id| suppliers << { "supplier_id" => row["supplier_#{supplier_id}_id"], "supplier_name" => row["supplier_#{supplier_id}_name"], "supplier_cost" => row["supplier_#{supplier_id}_cost"], "supplier_ref" => row["supplier_#{supplier_id}_ref"] } end suppliers end end </code>
class ProductsController < ApplicationController
  require 'csv'

  def index
    @csv_data = session[:csv_data] || []  # Load uploaded CSV data from session
  end

  def import
    if params[:file].present?
      csv_file = params[:file]
      @csv_data = []

      CSV.foreach(csv_file.path, headers: true) do |row|
        relevant_data = {
          "sku_code" => row["sku_code"],
          "product_id" => row["product_id"],
          "product_title" => row["product_title"],
          "sell_price" => row["sell_price"],
          "tax_rate" => row["tax_rate"],
          "suppliers" => parse_supplier_data(row)
        }
        @csv_data << relevant_data
      end

      session[:csv_data] = @csv_data

      respond_to do |format|
        format.turbo_stream { render turbo_stream: [
          turbo_stream.replace("products_table", partial: "products_table", locals: { csv_data: @csv_data }),
          turbo_stream.replace("action_buttons", partial: "action_buttons")
        ]}
        format.html { redirect_to products_path, notice: "CSV uploaded and parsed successfully." }
      end
    else
      redirect_to products_path, alert: "Please upload a valid CSV file."
    end
  rescue StandardError => e
    Rails.logger.error "Error processing CSV: #{e.message}"
    redirect_to products_path, alert: "Error processing CSV: #{e.message}"
  end

  def clear
    session[:csv_data] = nil  # Clear the CSV data stored in the session
    redirect_to products_path, notice: "Data cleared. You can upload a new CSV."
  end

  private

  def parse_supplier_data(row)
    suppliers = []
    supplier_columns = row.headers.select { |col| col.match?(/supplier_d+_/) }
    supplier_ids = supplier_columns.map { |col| col[/supplier_(d+)_/, 1] }.uniq

    supplier_ids.each do |supplier_id|
      suppliers << {
        "supplier_id" => row["supplier_#{supplier_id}_id"],
        "supplier_name" => row["supplier_#{supplier_id}_name"],
        "supplier_cost" => row["supplier_#{supplier_id}_cost"],
        "supplier_ref" => row["supplier_#{supplier_id}_ref"]
      }
    end

    suppliers
  end
end

Code in the View (index.html.erb):
erb

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><h1>Manage Supplier Associations</h1>
<% if @csv_data.blank? %>
<!-- File Upload Form -->
<div class="card">
<div class="card-body">
<h3>Upload a CSV File</h3>
<%= form_with url: import_products_path, method: :post, multipart: true, class: "mb-4" do |f| %>
<div class="mb-3">
<%= f.file_field :file, class: "form-control", accept: ".csv" %>
</div>
<div>
<%= f.submit "Upload CSV", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
<% else %>
<!-- Table Section -->
<div id="products_table">
<%= render partial: "products_table", locals: { csv_data: @csv_data } %>
</div>
<!-- Buttons Section -->
<div id="action_buttons" class="mt-3">
<%= link_to "Export CSV", export_products_path, class: "btn btn-secondary" %>
<%= link_to "Clear Data", clear_products_path, method: :get, class: "btn btn-danger" %>
</div>
<% end %>
</code>
<code><h1>Manage Supplier Associations</h1> <% if @csv_data.blank? %> <!-- File Upload Form --> <div class="card"> <div class="card-body"> <h3>Upload a CSV File</h3> <%= form_with url: import_products_path, method: :post, multipart: true, class: "mb-4" do |f| %> <div class="mb-3"> <%= f.file_field :file, class: "form-control", accept: ".csv" %> </div> <div> <%= f.submit "Upload CSV", class: "btn btn-primary" %> </div> <% end %> </div> </div> <% else %> <!-- Table Section --> <div id="products_table"> <%= render partial: "products_table", locals: { csv_data: @csv_data } %> </div> <!-- Buttons Section --> <div id="action_buttons" class="mt-3"> <%= link_to "Export CSV", export_products_path, class: "btn btn-secondary" %> <%= link_to "Clear Data", clear_products_path, method: :get, class: "btn btn-danger" %> </div> <% end %> </code>
<h1>Manage Supplier Associations</h1>

<% if @csv_data.blank? %>
  <!-- File Upload Form -->
  <div class="card">
    <div class="card-body">
      <h3>Upload a CSV File</h3>
      <%= form_with url: import_products_path, method: :post, multipart: true, class: "mb-4" do |f| %>
        <div class="mb-3">
          <%= f.file_field :file, class: "form-control", accept: ".csv" %>
        </div>
        <div>
          <%= f.submit "Upload CSV", class: "btn btn-primary" %>
        </div>
      <% end %>
    </div>
  </div>
<% else %>
  <!-- Table Section -->
  <div id="products_table">
    <%= render partial: "products_table", locals: { csv_data: @csv_data } %>
  </div>

  <!-- Buttons Section -->
  <div id="action_buttons" class="mt-3">
    <%= link_to "Export CSV", export_products_path, class: "btn btn-secondary" %>
    <%= link_to "Clear Data", clear_products_path, method: :get, class: "btn btn-danger" %>
  </div>
<% end %>

roblem:
When I upload the CSV and it is processed, the Turbo Stream updates the table and buttons, but the changes do not appear until I manually refresh the page. I expect the page to automatically update without the need for a manual refresh after the file is uploaded.

What I have tried:
Using redirect_to after uploading the file to re-render the page.
Wrapping the Turbo Stream updates in turbo_stream.replace to replace the relevant elements (products_table and action_buttons).
Ensuring that the Turbo Stream is properly set up in my controller.
Ensuring the partials are being rendered correctly with the updated @csv_data.
What I need help with:
Why does the page not automatically update after the CSV is uploaded?
How can I make sure the page updates without needing a manual refresh?
Any help would be greatly appreciated! Thanks!

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật