2

I'm using rails 4.2.4 and after generating a basic product scaffold I cant seem to get the gem jquery-datatables-rails. I'm using the github readme along with the railscast episode to try and get it working with no luck at all.

http://railscasts.com/episodes/340-datatables

https://github.com/rweng/jquery-datatables-rails

Gemfile

gem 'jquery-datatables-rails', '~> 3.3.0'

application.js

//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require turbolinks
//= require_tree .

jQuery -> $('.datatable').DataTable();

application.css

*= require dataTables/jquery.dataTables
*= require_tree .
*= require_self

index.html.erb

<table class="datatable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>      
    </tr>
  </thead>

  <tbody>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= product.price %></td>
      </tr>
    <% end %>
  </tbody>
</table>

I have tried directly referencing the github repo in my gemfile. The generate install doesn't seem add the requires in properly either way so I have put them in manually.

tet5uo
  • 139
  • 1
  • 1
  • 12

2 Answers2

3

Managed to fix this by putting this script into the view

<script>
  $(document).ready(function() {
    $('.datatable').dataTable();
  } );
</script>
tet5uo
  • 139
  • 1
  • 1
  • 12
0

For future readers, you can do this instead of the accepted answer above. You can dump this straight into your appliation.js file - i don't like the idea of having the scripts in your view as the answer above suggests:

Add to Application.js

$(document).ready(function(){
  $("table[role='datatable']").each(function(){
    $(this).DataTable({
      processing: true      
    });
  });  
})
  • loads only after the document is ready.
  • acts on a role element, rather than an id - which can get cumbersome when you wish to apply the same logic on a few tables.

Don't forget to add a role='datatable' to your html table.

  • Add role='datatable' to your table.
  • ensure you have a theader element and also a
  • tbody element

Add role to table

BenKoshy
  • 33,477
  • 14
  • 111
  • 80