Search code examples
jqueryruby-on-railscoffeescriptdatatables

DataTables only loads on page refresh


In my Rails 4 application, if I visit a page with a DataTable from another URL, it loads just the plain HTML table. But, if I reload the page, the DataTable appears and functions normally. Here's the coffeescript I'm using to run the table.

app/assets/javascript/employees.coffee

jQuery ->

  $('#margin-table1').dataTable().fnDestroy() # prevent duplication error
  $('#margin-table1').dataTable
    'dom' : 'TC<"clear">lftip'
    'bPaginate' : false
    'bInfo' : false
    tableTools: {
      "sSwfPath": "/copy_csv_xls_pdf.swf"
    }

app/assets/javascript/application.js

//= require bootstrap
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require dataTables.colVis
//= require dataTables.tableTools
//= require jquery.purr
//= require dataTables/jquery.dataTables
//= require chartkick
//= require_tree .

app/assets/stylesheets/application.css

*= require_tree .
*= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
*= require dataTables/extras/dataTables.colVis
*= require dataTables/extras/dataTables.tableTools
*= require_self

Solution

  • Okay, I think I understand your problem enough to provide an answer. The thing about using turbolinks is that most plugins and libraries that bind to the document ready event stop working, since turbolinks prevents the browser from reloading the page. There are tricks to fix those issues, but the easiest way to fix it is to use jquery.turbolinks.

    To use it, just add this to your Gemfile

    gem 'jquery-turbolinks'
    

    and this to your assets/javascripts/application.js file:

    //= require jquery.turbolinks
    

    and restart your server, it will be working properly.