Skip to content

Instantly share code, notes, and snippets.

@kagemusha
Created January 6, 2012 01:42
Show Gist options
  • Save kagemusha/1568472 to your computer and use it in GitHub Desktop.
Save kagemusha/1568472 to your computer and use it in GitHub Desktop.
JQuery Datatables, Rails Basic Server-side processing Example with Json obj, Custom Data Display
Tested on: Datatable 1.8.2, Rails 3.1.3
This example uses Coffeescript and Haml (you should too :-) )
The following is an example of Datatables server-side processing of a table
which displays a user's song list including the songs' artist names. In
Rails, Song and Artist are ActiveRecord models in a one artist-many song relat.
1a. the Rails controller code
class SongsController < ApplicationController
...
def datatable_my_songs
@songs = current_user.songlist.songs
data = Hash.new
#pagination - see doc
#data["sEcho"] = see doc
#data["iTotalRecords"] = see doc
#data["iTotalDisplayRecords"] = see doc
data["aaData"] = @songs.as_json :include=>{:artist=>{:only=>:name}}
render :json=>data.to_json
end
Notes:
- if no "aaData" prop will get error described here https://gist.github.com/1661626
- need :include to load related obj data, more here: https://gist.github.com/1542498
1a. Add a Rails Route
Something like:
match "my_songs" => "songs#datatable_my_songs"
2. Client Side
##assets/javascripts/songs.js.coffee
initSongTable = ->
$("#mySongsTable").dataTable
"bPaginate": false,
"bServerSide": true,
"sAjaxSource": "/my_songs", #should be the named rails route
"aoColumns": [
{ "mDataProp": "song.name" },
{ "mDataProp": "song.artist.name" },
{ "mDataProp": null}
]
"fnServerData": ( sSource, aoData, fnCallback ) ->
$.getJSON sSource, aoData, (json) ->
#Do whatever additional processing you want on the callback
#then tell DataTables
fnCallback(json)
"fnRowCallback": (nRow, aData, iDisplayIndex) ->
obj = aData.song
$('td:eq(2)', nRow).html objLinksTmpl("song", obj)
nRow
3. Html Page
Make sure you have same num of %th elems as aoColumns (each of which needs mDataProp - which can be null - or get popup warning here https://gist.github.com/1660712)
I use a partial, though you can write a table directly. Remember to call your table init function. I use a helper method js(jsFunctionName) as detailed below.
##songs/index.html.haml
= render :partial=>"shared/dataTable", :locals =>{:tableId=>"mySongsTable", :columns=>["Name", "Artist","Actions"]}
js "initSongTable"
##shared/_dataTable.rb
%table{:id=>tableId}
%thead
%tr
- columns.each do |col|
%th #{col}
%tbody
##helpers/html_helper.rb
module HtmlHelper
def js(function)
function += (!function.end_with?("()") ? "()" : "" )
fn = <<-STR
<script>
$(function(){
var root = window || global;
root.#{function};
});
</script>
STR
fn.html_safe
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment