Class: UcbRails::BaseDatatable

Inherits:
Object
  • Object
show all
Defined in:
app/datatables/ucb_rails/base_datatable.rb

Overview

Base class for server-side processing for datatable.js

Inspired by railscasts.com/episodes/340-datatables

Documentation on datatable.js parameters: datatables.net/usage/server-side

class MyUsersController < BaseController

def index
  respond_to do |format|
    format.html
    format.json { render json: MyUsersDatatable.new(view_context) }
  end
end

end

class MyUserDatatable < BaseDatatable

private

def default_scope
  User
end

def column_names
  @column_names ||= %w[first_name last_name]
end

# Must return valid argument(s) to ActiveRecord::Relation#where()
# (Won't be called if _search_term_ is blank)
def search(search_term)
  where("first_name like :search or last_name like :search", search: "#{search_term}%")
end

def record_to_data(user)
  [
    h(user.first_name),
    h(user.last_name),
    link_to("Edit", edit_admin_user_path(user), :id => dom_id(user)),
  ]
end

end

Direct Known Subclasses

UsersDatatable

Instance Method Summary collapse

Constructor Details

#initialize(view) ⇒ BaseDatatable

Returns a new instance of BaseDatatable.



48
49
50
# File 'app/datatables/ucb_rails/base_datatable.rb', line 48

def initialize(view)
  @view = view
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object (private)

Delegate unknown methods to the view. These are mostly standard View Helper methods.



111
112
113
# File 'app/datatables/ucb_rails/base_datatable.rb', line 111

def method_missing(*args, &block)
  @view.send(*args, &block)
end

Instance Method Details

#as_json(options = {}) ⇒ Object

Data structure required by datatable.js server calls



53
54
55
56
57
58
59
60
# File 'app/datatables/ucb_rails/base_datatable.rb', line 53

def as_json(options = {})
  {
    sEcho: params[:sEcho].to_i,
    iTotalRecords: default_scope.count,
    iTotalDisplayRecords: records.total_count,
    aaData: data
  }
end