Skip to content

Instantly share code, notes, and snippets.

@supairish
Forked from bgkittrell/gist:704674
Created June 18, 2011 18:32
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 supairish/1033379 to your computer and use it in GitHub Desktop.
Save supairish/1033379 to your computer and use it in GitHub Desktop.
Reorder Multiple Elements ala Netflix
images = @album.image_assignments
changed = Array.new
# Get the images that changed order
for image in images
order = params["order_#{image.image_id}".to_sym]
if !order.blank? && order =~ /^\d+$/ && image.position.to_i != order.to_i
image.position = order.to_i
changed << image
end
end
# Resort based on new position
changed.sort! { |a, b| a.position <=> b.position }
# Remove the changed images
for image in changed
images.delete_if { |a| a.id == image.id }
end
# Reinsert the changed images
for image in changed
images.insert(image.position - 1, image)
end
idx = 1
# Reindex all positions, only saving what actually changed
for image in images.compact
image.position = idx
image.save if image.position_changed?
idx += 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment