Skip to content

Instantly share code, notes, and snippets.

@vincentlkl
Last active July 20, 2016 13:21
Show Gist options
  • Save vincentlkl/9340e24593e3010b51d2596e42854224 to your computer and use it in GitHub Desktop.
Save vincentlkl/9340e24593e3010b51d2596e42854224 to your computer and use it in GitHub Desktop.
Ajax Datatable
class ItemsDatatable
delegate :params, :h, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Item.count,
iTotalDisplayRecords: items.total_entries,
aaData: data
}
end
private
def data
items.map do |item|
[
item.id,
]
end
end
def items
@items ||= fetch_items
end
def fetch_items
items = Item.order("#{sort_column} #{sort_direction}")
items = items.page(page).per_page(per_page)
if params[:sSearch].present?
items = items.where("CAST(items.id AS TEXT) ilike :search", search: "%#{params[:sSearch]}%")
end
items
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[id]
sort_col = "items.#{columns[params[:iSortCol_0].to_i]}"
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment