Skip to content

DataTables on Ruby on Rails

December 16, 2013

Below is short tutorial on how to use the famous DataTables jQuery plugin. You can find additional information on datatables.net

Prerequisites

This tutorial has been successfully tested on below environments but should work

  • Rails 2, 3 and greater
  • Ruby 1.8.7 and greater
  • jQuery 1.9.0 and greater
  • DataTables 1.9.4

Users on rails 2 and less are required to download  jQuery 1.9.0 or greater (preferably the minified version) on jquey.com and place the file under the public folder :

rails 2 : public/javascripts/

rails 3 and greater : assests/javascripts/

Installation

(1) Download the DataTables jQuery plugin from http://www.datatables.net/

(2) Extract the content on your desired location

(3) Copy all files in media into your public folder

==files to copy
media/images/*
media/js/*
media/css/*

==rails public folder
rails 2 :
public/javascripts
public/images
public/stylesheets

rails 3+ :
assets/javascripts
assets/images
assets/stylesheets

(4) Copy the following files in your corresponding rails public folder

==files to copy
extra/TableTools/media/js/TableTools.min.js
extra/TableTools/media/js/ZeroClipboard
extra/TableTools/media/css/TableTools_JUI.css
extra/TableTools/media/css/TableTools.css
extra/TableTools/media/sw/copy_csv_xls_pdf.swf (this file goes into the public folder on both rails 2 & 3+)

==public folder
rails 2 :
public/javascripts
public/images
public/stylesheets

rails 3+:
assets/javascripts
assets/images
assets/stylesheets

(5) Set your layout :

<%= stylesheet_link_tag "jquery.dataTables", "TableTools", "TableTools_JUI"%>
<%= javascript_include_tag "jquery", "jquery.dataTables","TableTools.min" %>

(6) Set your controller & view

# app/controllers/list_controller.rb
def index
  @list = Product.find(:all)
  respond_to do |format|
    format.html {render: @list }
  end
end

# app/views/list/index.html.erb

<script>

  $(document).ready(function() {
    $('#list').dataTable({
      "sDom": 'T<"clear">lfrtip',
      "oTableTools": {
      "sSwfPath": "copy_csv_xls_pdf.swf"
      }
    });
  } );
</script>

<h3>List</h3>
<table id="list">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
    </tr>
  </thead>
  <tbody>
    <% @list.each do |i| %>
      <tr>
        <td><%= i.col1 %></td>
        <td><%= i.col2 %></td>
      </tr>
    <% end %>
  </tbody>
</table>
<br />

From → Ruby on Rails

Leave a Comment

Leave a comment