如何使Rails中Ajax-Datatable搭配Turbolinks重访页面时正常工作?
Hey there, let's work through this frustrating issue you're hitting with your DataTable. That flash of old data followed by an empty table when navigating back is a classic pain point when combining Rails Turbo (or Turbolinks) with dynamic JS components like DataTables. Here's what's happening and how to fix it:
What's Causing This?
- Turbo keeps a cached version of previously visited pages. When you navigate back, it first renders that cached HTML (with your old table data) before processing any new JS.
- Your original
$ ->(document ready) code only runs once on the initial page load. When returning via Turbo, it either re-initializes the DataTable incorrectly or fails to trigger the AJAX request to fetch fresh data—leaving you with an empty table after the cached content clears.
Step-by-Step Fixes
1. Use Turbo's Load Event + Destroy Existing DataTable Instances
Replace your document ready handler with Turbo's turbo:load event, and destroy any existing DataTable instances before reinitializing. This ensures you start fresh every time the page loads (including when navigating back):
$(document).on 'turbo:load', -> # Check if the table is already a DataTable instance existingTable = $('#cashflows_table').DataTable() if existingTable? existingTable.destroy() # Re-initialize the DataTable $('#cashflows_table').dataTable processing: true serverSide: true select: true ajax: $('#cashflows_table').data('source') # Adjust this to match your AJAX source # Add your other DataTables options here (columns, ordering, etc.)
2. Optional: Disable Turbo Caching for the Page
If you want to eliminate the old data flash entirely, tell Turbo not to cache this page. Add this meta tag to your view's <head> section:
<%# In your DataTable page's view template %> <meta name="turbo-cache-control" content="no-cache">
This forces Turbo to fetch a fresh version of the page every time you navigate back, though it adds a small server request overhead.
3. Verify Your Server-Side Endpoint
Double-check that your Rails controller action (handling the DataTable AJAX request) is properly responding to all DataTables parameters (like draw, start, length). The ajax-datatable gem expects a specific JSON format—make sure your controller is returning consistent, valid data on every request, even when navigating back.
Why This Works
By using turbo:load, you ensure your DataTable initialization runs every time the page is rendered (including cached Turbo loads). Destroying existing instances prevents conflicts between the cached table and the new initialization, ensuring the AJAX request fires correctly to populate fresh data.
内容的提问来源于stack exchange,提问作者muso mwale

