Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active September 18, 2015 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwan/aa36b23502c58ce91f31 to your computer and use it in GitHub Desktop.
Save iwan/aa36b23502c58ce91f31 to your computer and use it in GitHub Desktop.
Re-sort table rows using buttons/links and jquery on Ruby on Rails

Description

Code snippets used in a Ruby On Rails project to allow the user to reorder a list (in this case rows of a table) using buttons or links. On user click an asynchronous JavaScript call will be fired to inform the database, and on view the elements position is switched. Use 'shift' key to put the element/item on top or bottom of the list/table.

Dependences

The RoR project use [acts_as_list]{https://github.com/swanandp/acts_as_list} gem and jQuery.

$(document).ready ->
$("a.sortable").on "click", (e) ->
e.preventDefault()
id = $(this).data('id')
dir = $(this).data('direction') # "up" or "down"
sel = $("#item_#{id}") # selector of current
$.ajax
url: "/activities/#{id}/move"
data:
direction: dir
shiftkey: e.shiftKey
dataType: "json"
success: (data, textStatus, jqXHR) ->
if e.shiftKey
if dir=="up"
$("tbody tr.sortable-row:first").before(sel)
else # "down"
$("tbody tr.sortable-row:last").after(sel)
else
if dir=="up"
sel.prev("tr.sortable-row").before(sel)
else # "down"
sel.next("tr.sortable-row").after(sel)
error: (jqXHR, textStatus, errorThrown) ->
$('body').append "AJAX Error: #{textStatus}"
...
def move
# {"direction"=>"up", "shiftkey"=>"false", "id"=>"42"}
if params[:shiftkey]=="true"
if params[:direction]=="up"
@activity.move_to_top
else
@activity.move_to_bottom
end
else
if params[:direction]=="up"
@activity.move_higher
else
@activity.move_lower
end
end
end
...
class Activity < ActiveRecord::Base
acts_as_list
...
end
...
%table.table.table-bordered.table-condensed
%thead
%tr
%th= t(".pos")
%th= t("activities.attributes.name")
...
%tbody
- @activities.each do |activity|
%tr.sortable-row{id: "item_#{activity.id}"}
%td
= link_to "up", move_activity_path(activity, direction: "up"), class: "sortable", data: { direction: :up, id: activity.id }
= link_to "down", move_activity_path(activity, direction: "down"), class: "sortable", data: { direction: :down, id: activity.id }
%td= link_to activity.name, activity
...
# views/activities/move.json
{ }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment