Permalink
Browse files

Working Solution

  • Loading branch information...
1 parent 5bfbddb commit 406b1565e75701462acd8eefe29aa3ae7ff5fbb3 @matenia committed Sep 24, 2011
View
25 rails3_example/app/controllers/home_controller.rb
@@ -1,5 +1,30 @@
class HomeController < ApplicationController
+
def index
+
+ end
+
+ def savesort
+ neworder = JSON.parse(params[:set])
+ prev_item = nil
+ neworder.each do |item|
+ dbitem = Category.find(item['id'])
+ prev_item.nil? ? dbitem.move_to_root : dbitem.move_to_right_of(prev_item)
+ sort_children(item, dbitem) unless item['children'].nil?
+ prev_item = dbitem
+ end
+ Category.rebuild!
+ render :nothing => true
+ end
+
+ def sort_children(element,dbitem)
+ prevchild = nil
+ element['children'].each do |child|
+ childitem = Category.find(child['id'])
+ prevchild.nil? ? childitem.move_to_child_of(dbitem) : childitem.move_to_right_of(prevchild)
+ sort_children(child, childitem) unless child['children'].nil?
+ prevchild = childitem
+ end
end
end
View
40 rails3_example/app/views/home/index.html.erb
@@ -1,3 +1,43 @@
<% content_for :head do -%>
<%= javascript_include_tag 'nestedsortables.min' %>
+ <style type="text/css" media="screen">
+ #sortable{width:300px;}
+ ul{margin-bottom:0px;}
+ .highlight{background-color:#d6d88e;}
+ </style>
+ <script type="text/javascript" charset="utf-8">
+ $(function() {
+ $("#sortable").nestedSortable({
+ listType: 'ul',
+ items: 'li',
+ placeholder: "highlight",
+ forcePlaceholderSize: true,
+ handle: 'span',
+ helper: 'clone',
+ opacity: .6,
+ revert: 250,
+ tabSize: 25,
+ tolerance: 'pointer',
+ toleranceElement: '> span'
+ });
+ $("#sortable").disableSelection(); // make links not clickable
+ $('#serialize').click(function (){
+ var c = {set : JSON.stringify($('#sortable').nestedSortable('toHierarchy', {startDepthCount: 0}))};
+ $.post("savesort", c, $('#output').html('<p id="flash_notice">Saved Successfully</p>'));
+ return false;
+ });
+ });
+ </script>
<% end -%>
+
+<h1>Category Sorting Example</h1>
+<p>Drag and drop the categories into a nested set then hit save</p>
+<h3><a href='#' id='serialize'>Save Sorted Elements</a></h3>
+<ul id='sortable'>
+ <% for cat in Category.roots %>
+ <li id='category_<%= cat.id %>'>
+ <span><%= cat.name %></span>
+ <%= render 'shared/children', :item => cat unless cat.leaf? %>
+ </li>
+ <% end -%>
+</ul>
View
8 rails3_example/app/views/shared/_children.html.erb
@@ -0,0 +1,8 @@
+<ul>
+ <% item.children.each do |child| %>
+ <li id='category_<%=child.id %>'>
+ <span><%= child.name %></span>
+ <%= render 'shared/children', :item => child unless child.leaf? %>
+ </li>
+ <% end -%>
+</ul>
View
3 rails3_example/public/stylesheets/application.css
@@ -1,3 +1,6 @@
+body {
+ color:#444;
+}
a img {
border: none;
}

0 comments on commit 406b156

Please sign in to comment.