I looked at this railscast.
Using that as a template Im using datatables, bootstrap, will_paginate in my rails app.
My model is called "Demo" Here is the code:
application.js
...............
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require dataTables/jquery.dataTables
//= require_tree .
demos.js.coffee
jQuery ->
$("#demos").dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
bProcessing: true
bServerSide: true
sAjaxSource: $('#demos').data('source')
I added a class called "ModelDatatables" in the project in order to let any model use the datatable in its view. class ModelsDatatable delegate :params, :link_to, :to => :@view attr_accessor :model_name, :models
def initialize(view, model_name)
puts "nitializing Model Datatables with modelname = #{model_name}"
@view = view
@model_name = model_name
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i, #variable needed by Datatables server
iTotalRecords: @model_name.count, #variable needed by Datatables server
iTotalDisplayRecords: models.total_entries,
aaData: data
}
end
private #====================================================================
def data
models.map do |m|
[
link_to(m.name, m)
]
end
end
def models
@models ||= fetch_models
end
def fetch_models
mod_instance = @model_name.order("#{sort_column} #{sort_direction}")
mod_instance = mod_instance.page(page).per_page(per_page)
if params[:sSearch].present?
mod_instance = mod_instance.where("name like :search or category like :search",
search: "%#{params[:sSearch]}%")
end
mod_instance
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
att_array = @model_name.attribute_names.to_a
columns = att_array
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
In my controller Im trying to use the datatables class like so Demo_controller.rb
def index
respond_to do |format|
format.html
format.json { render json: ModelsDatatable.new(view_context, Demo ) }
end
end
Views:
demos/index.html.erb
<%- model_class = Demo -%>
<div class="page-header">
<h1><%=t '.title', :default => model_class.model_name.human.pluralize.titleize %></h1>
</div>
<table class="table table-striped display" id="demos" data-source="<%= demos_url(format: "json") %>" >
<thead>
<tr>
.......
</thead>
<tbody>
.......
</tbody>
</table>
When I run this on my browser. I get this error:
SyntaxError: unexpected {
(in /Users/Xxxxxx/Desktop/xxxxxxxxx/app/assets/javascripts/demos.js.coffee)
Extracted source (around line #37):
<%= javascript_include_tag "application" %>
app/views/layouts/application.html.erb:37:in
`_app_views_layouts_application_html_erb__2549661732362878565_70299008379240'
app/controllers/demos_controller.rb:8:in `index'
Not sure what to do next. Can someone give a hand?
Thanks