Created
February 23, 2014 16:54
-
-
Save geordee/9173911 to your computer and use it in GitHub Desktop.
A generic data table class to support rendering DataTables from remote. Most of the code from RailsCasts #340 (http://railscasts.com/episodes/340-datatables). Inherit this class and override the columns, records and data methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GenericDatatable | |
delegate :params, :h, :link_to, :raw, to: :@view | |
def initialize(view, records) | |
@view = view | |
@records = records | |
end | |
def as_json(options = {}) | |
{ | |
sEcho: params[:sEcho].to_i, | |
iTotalRecords: records.count, | |
iTotalDisplayRecords: records.total_entries, | |
aaData: data | |
} | |
end | |
private | |
# override this method in child class | |
def data | |
end | |
# override this method in child class | |
def records | |
end | |
# override this method in child class | |
def columns | |
%w[] | |
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[params[:iSortCol_0].to_i] | |
end | |
def sort_direction | |
params[:sSortDir_0] == "desc" ? "desc" : "asc" | |
end | |
def column_search | |
search_string = [] | |
params.keys.map {|x| x if params[x].present? and x.include? "sSearch_"}.compact.each do |search| | |
index = search.split("_").last.to_i | |
search_string << "#{columns[index]} ilike '%#{params[search]}%'" | |
end | |
search_string.join(' and ') | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ItemsDatatable < GenericDatatable | |
private | |
def data | |
records.map do |item| | |
[ item.id, | |
link_to(item.code, item), | |
item.name, | |
item.category, | |
item.location, | |
item.vendor | |
] | |
end | |
end | |
def records | |
@records ||= Item.all | |
items = @records.order("#{sort_column} #{sort_direction}") | |
items = items.page(page).per_page(per_page) | |
items = items.where(column_search).references(:items) | |
if params[:sSearch].present? | |
items = items.where("name ilike :search or category ilike :search", search: "%#{params[:sSearch]}%") | |
end | |
items | |
end | |
def columns | |
%w[items.id items.code items.name items.category items.location items.vendor] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment