I have created a very simple rails application with one class Users. Here are the relevant pieces, I think:
Gem file ( relevant portions ) gem 'rails', '~> 5.0.0' gem 'sqlite3' gem 'puma', '~> 3.0' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.2' # Use jquery as the JavaScript library gem 'jquery-rails' gem 'turbolinks', '~> 5' gem 'jquery-turbolinks' gem 'jbuilder', '~> 2.5'
gem 'jquery-datatables-rails', '~> 3.3.0'
application.js
//
//= require_self
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require jquery.turbolinks
//= require turbolinks
//= require_tree .
application.css
*= require_tree .
*= require dataTables/jquery.dataTables
*= require_self
index.html.erb
<p id="notice"><%= notice %></p>
<h1>Users</h1>
<table id="users">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New User', new_user_path %>
users.coffee ( I've tried naming this users.js.coffee, to no avail )
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
jQuery ->
$('#users').dataTable()
"sPaginationType": "bootstrap"
routes.rb
Rails.application.routes.draw do
resources :users
root 'users#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
end
...
When I bundle install, then rails db:migrate, then rails server, I get the data showing, but without anything I expect from DataTables, viz.
How do I get the sort buttons, search area, row highlighting, and pagination to show?
Found the problem while looking over the browser debug window. I was using a colspan in the header and three td's in the table body. That caused an exception in jQuery data tables because the number of elements in the header was not equal to the number in the table.
I had to add:
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
at the top of the index.html.erb, and
<script>
$(function(){
$("#user-table").dataTable();
});
</script>
just above where the link for New User was to make it format. I would like to know how to move these into either a coffee file or other external file if possible.