Skip to content

Instantly share code, notes, and snippets.

@mgrigajtis
Created August 8, 2014 20:05
Show Gist options
  • Save mgrigajtis/144897e0a20c890e5891 to your computer and use it in GitHub Desktop.
Save mgrigajtis/144897e0a20c890e5891 to your computer and use it in GitHub Desktop.
DataTables in Rails
In the CoffeeScript:
# Row clicking
selected_id = ''
$('#table_name tbody').on "click", "tr", ->
if $(event.target.parentNode).hasClass("info")
$(event.target.parentNode).removeClass "info"
selected_frame_order = ''
else
table_name.$("tr.info").removeClass "info"
$(event.target.parentNode).addClass "info"
row = table_name.row(this).data()
$('#btn_show').removeClass('disabled')
$('#btn_edit').removeClass('disabled')
$('#btn_destroy').removeClass('disabled')
selected_id = row[0]
table_name = $("#shipment_table").DataTable
bRetrieve: true
processing: true
serverSide: true
filter: false
ajax:
url: $('#table_name').data('source')
data: (d) ->
return
order: [[ 0, "desc" ]]
In the controller:
def index
respond_to do |format|
format.html { @current_screen = title }
format.json { render json: DatatableName.new(view_context) }
end
end
In the DataTable File:
class DatatableName
delegate :params, :h, :link_to, :number_to_currency, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
{
draw: params[:sEcho].to_i,
recordsTotal: ObjectName.count,
recordsFiltered: objects.total_entries,
data: data
}
end
private
def data
objects.map do |o|
[
o.id,
o.name,
o.description
]
end
end
def objects
@objects ||= fetch_objects
end
def fetch_objects
ObjectName.all.page(page).per_page(per_page)
end
def page
params[:start].to_i / per_page + 1
end
def per_page
params[:length].to_i > 0 ? params[:length].to_i : 50
end
def sort_column
columns = %w(id name description)
columns[ params[:order]['0']['column'].to_i]
end
def sort_direction
params[:order]['0']['dir'] == 'desc' ? 'desc' : 'asc'
end
end
In the veiw:
<table id="table_name" class="hover row-border compact" width="100%" data-source="<%= objects_url(format: "json") %>">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In the JSON file:
json.array!(@objects) do |object|
json.id object.id
json.name object.name
json.description object.description
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment