Screencast: DataTables

DataTables erleichtert die Erstellung von Tabellen in HTML und unterstützt dabei seitenweise Navigation, Sortierung und Suchen. Ryan zeigt in diesem Screencast wie es in Rails eingesetzt werden kann.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]
group :assets do
gem ‚jquery-datatables-rails‘, github: ‚rweng/jquery-datatables-rails‘
gem ‚jquery-ui-rails‘
end

gem ‚will_paginate‘
[/ruby]

app/assets/javascripts/application.js

[javascript]
//= require dataTables/jquery.dataTables
[/javascript]

app/assets/stylesheets/application.css

[css]
/*
*= require jquery.ui.core
*= require jquery.ui.theme
*= require dataTables/src/demo_table_jui
*/
[/css]

app/assets/javascripts/products.js.coffee

[javascript]
jQuery ->
$(‚#products‘).dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
bProcessing: true
bServerSide: true
sAjaxSource: $(‚#products‘).data(’source‘)
[/javascript]

views/products/index.html.erb

[html]
<table id="products" class="display" data-source="<%= products_url(format: "json") %>">
<thead>
<tr>
<th>Product Name</th>
<th>Category</th>
<th>Release Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
[/html]

products_controller.rb

[ruby]
def index
respond_to do |format|
format.html
format.json { render json: ProductsDatatable.new(view_context) }
end
end
[/ruby]

app/datatables/products_datatable.rb

[ruby]
class ProductsDatatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view

def initialize(view)
@view = view
end

def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Product.count,
iTotalDisplayRecords: products.total_entries,
aaData: data
}
end

private

def data
products.map do |product|
[
link_to(product.name, product),
h(product.category),
h(product.released_on.strftime("%B %e, %Y")),
number_to_currency(product.price)
]
end
end

def products
@products ||= fetch_products
end

def fetch_products
products = Product.order("#{sort_column} #{sort_direction}")
products = products.page(page).per_page(per_page)
if params[:sSearch].present?
products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
products
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
columns = %w[name category released_on price]
columns[params[:iSortCol_0].to_i]
end

def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
[/ruby]

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.