Created
September 21, 2012 04:15
-
-
Save pzgz/3759691 to your computer and use it in GitHub Desktop.
Decode datatables ajax request URL in ruby controller
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
# Process AJAX request generated by jquery datatables plugin, prepare an object which contains information to be used in | |
# ActiveRecord operation, result object properties tbd | |
def decode_datatables_req | |
cols_count = params['iColumns'].to_i | |
row_start = params['iDisplayStart'].to_i | |
rows_per_page = params['iDisplayLength'].to_i | |
search_text = params['sSearch'] | |
sort_cols_count = params['iSortingCols'].to_i | |
columns = (0..cols_count-1).map { |i| params["mDataProp_#{i}"] } | |
# Suffix table name by grabbing from current control, to avoid ambigious col issue which might occured during ordering | |
sort_columns = (0..sort_cols_count-1).map do |i| | |
col_name = columns[params["iSortCol_#{i}"].to_i] | |
col_name = "#{params[:controller]}.#{col_name}" unless col_name.index('.') | |
{ | |
:col => col_name, | |
:direction => params["sSortDir_#{i}"] | |
} | |
end | |
# Now let's rock it and do the processing | |
{ | |
per_page: rows_per_page, | |
page: row_start/rows_per_page + 1, | |
columns: columns, | |
cols_count: cols_count, | |
sort_cols_count: sort_cols_count, | |
sort_columns: sort_columns, | |
sort_statement: (sort_columns.map {|col| "#{col[:col]} #{col[:direction]}"}).join(', '), | |
search_text: search_text | |
} | |
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
def get_rows | |
dt = decode_datatables_req | |
# Extra filtering for type and branch id | |
where_array = [] | |
where_array << "branches.chinese_name like :keyword or branches.english_name like :keyword" unless params['keyword'].blank? | |
search_obj = { | |
:include => [], | |
:order => dt[:sort_statement], | |
:conditions => [where_array.join(' AND '), { :keyword => "%#{params['keyword']}%" }] | |
} | |
@total_rows = Branch.count(:all, search_obj) | |
@rows = Branch.page(dt[:page]).per(dt[:per_page]).find(:all, search_obj) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment