Skip to content

Instantly share code, notes, and snippets.

@robertjwhitney
Created July 3, 2012 03:37
Show Gist options
  • Save robertjwhitney/3037442 to your computer and use it in GitHub Desktop.
Save robertjwhitney/3037442 to your computer and use it in GitHub Desktop.
Simple drag/drop reordering of records in an ActiveAdmin view table
# http://stackoverflow.com/a/8936202
#
# ActiveAdmin already includes the necessary jquery in active_admin/base,
# so just add this to javascripts/active_admin.js after //= require active_admin/base
#
#
# Serialize and Sort
#
# model_name - you guessed it, the name of the model we are calling sort on.
# This is the actual variable name, no need to change it.
#
sendSortRequestOfModel = (model_name) ->
formData = $('#' + model_name + ' tbody').sortable('serialize')
formData += '&' + $('meta[name=csrf-param]').attr('content') +
'=' + encodeURIComponent($('meta[name=csrf-token]').attr('content'))
$.ajax
type: 'post'
data: formData
dataType: 'script'
url: '/admin/' + model_name + '/sort'
# Don't forget we are sorting Duck, so ducks refers specifically to that.
#
jQuery ($) ->
if $('body.admin_ducks.index').length
$( '#ducks tbody' ).disableSelection()
$( '#ducks tbody' ).sortable
axis: 'y'
cursor: 'move'
update: (event, ui) ->
sendSortRequestOfModel('ducks')
# admin/duck.rb
# Duck is the Model this particular file refers to.
# Ref. ActiveAdmin documentation for more.
# http://activeadmin.info/
ActiveAdmin.register Duck do
config.sort_order = 'position_asc'
...
collection_action :sort, :method => :post do
params[:story].each_with_index do |id, index|
Duck.update_all(['position=?', index+1], ['id=?', id])
end
render :nothing => true
end
end
@grzegorzblaszczyk
Copy link

works like a charm - thnx!

@mnassif
Copy link

mnassif commented May 9, 2013

You are the man. Great solution.

@BackSlasher
Copy link

In case someone else encounters this and considers implementing this for has_many - this is already done:
activeadmin/activeadmin#2656 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment