Created
June 21, 2012 05:27
-
-
Save codespore/2964024 to your computer and use it in GitHub Desktop.
Datatable Rails Implementation
This file contains hidden or 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
| # customers_controller | |
| def index | |
| index! do |format| | |
| format.html | |
| format.js do | |
| @customers = Customer.data_table(params) | |
| @iTotalRecords = Customer.count | |
| @iTotalDisplayRecords = @customers.length | |
| @sEcho = params[:sEcho].to_i | |
| render :partial => 'table' | |
| end | |
| end | |
| end | |
| # customer model | |
| # Data Table | |
| def self.data_table(params) | |
| keyword = "%#{params[:sSearch]}%" | |
| colName = ['first_name','last_name','passport_no','ic_no','email','primary_tel'] | |
| order = "#{colName[params[:iSortCol_0].to_i]} #{params[:sSortDir_0]}" | |
| relation = order(order) | |
| .limit(params[:iDisplayLength].to_i) | |
| .offset(params[:iDisplayStart].to_i) | |
| .where([ | |
| "id LIKE :keyword " + | |
| "OR first_name LIKE :keyword " + | |
| "OR last_name LIKE :keyword " + | |
| "OR CONCAT(first_name,' ',last_name) LIKE :keyword " + | |
| "OR passport_no LIKE :keyword " + | |
| "OR ic_no LIKE :keyword " + | |
| "OR email LIKE :keyword " + | |
| "OR primary_tel LIKE :keyword",:keyword => keyword] | |
| ) | |
| return relation | |
| end | |
| # _table.html.erb | |
| { | |
| "sEcho": <%=h @sEcho %>, | |
| "iTotalRecords": <%= @iTotalRecords %>, | |
| "iTotalDisplayRecords": <%= @iTotalDisplayRecords %>, | |
| "aaData" : [ | |
| <% @customers.each do |customer| %> | |
| [ "<%= link_to(customer.first_name, 'javascript:void(0)', :class => 'data-source', 'data-link' => customer_path(customer), 'data-id' => customer.id, 'data-name' => customer.full_name).gsub(/"/, "'") %>", | |
| "<%= customer.last_name %>", | |
| "<%= customer.passport_no %>", | |
| "<%= customer.ic_no %>", | |
| "<%= customer.email %>", | |
| "<%= customer.primary_tel %>" | |
| <%= "]," unless customer == @customers.last %> | |
| <% end %> | |
| <%= "]" unless @customers.size < 1 %> | |
| ] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment