Skip to content

Instantly share code, notes, and snippets.

@bgkittrell
Created November 18, 2010 05:53
Show Gist options
  • Save bgkittrell/704674 to your computer and use it in GitHub Desktop.
Save bgkittrell/704674 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