From 17b486f9e94e81e0b9513a721c2b2734ac66d0fb Mon Sep 17 00:00:00 2001 From: Christophe Vilayphiou Date: Fri, 11 May 2012 17:56:26 +0800 Subject: [PATCH] Fix bugs for shift_to and change items.rake for the missing position in db --- app/controllers/admin/items_controller.rb | 2 ++ app/models/item.rb | 17 +++++++++++++++++ lib/tasks/items.rake | 2 +- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/controllers/admin/items_controller.rb b/app/controllers/admin/items_controller.rb index eea82f9cd..1ea406405 100644 --- a/app/controllers/admin/items_controller.rb +++ b/app/controllers/admin/items_controller.rb @@ -17,6 +17,8 @@ class Admin::ItemsController < ApplicationController end def update_position + item = Item.find(params[:id]) + item.shift_to(params[:parent_id], params[:position]) render :nothing => true end diff --git a/app/models/item.rb b/app/models/item.rb index 4d6ca0010..cdf0f2fb1 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -35,6 +35,19 @@ class Item end a end + + def shift_to(new_parent, position) + unless self.parent_id.to_s.eql?(new_parent) && self.position.eql?(position.to_i) + new_parent = Item.find(new_parent) + current_position_sibling = find_by_parent_and_position(new_parent, position.to_i) + if current_position_sibling + current_position_sibling.at_bottom? ? move_below(current_position_sibling) : move_above(current_position_sibling) + elsif self.parent != new_parent + self.parent = new_parent + save! + end + end + end protected @@ -42,6 +55,10 @@ class Item self.path = (self.ancestors_and_self - [Item.root]).collect{|x| x.name unless x.root?}.join('/') end + def find_by_parent_and_position(parent, position) + parent.children.detect{|child| child.position == position} + end + # Enable the validation for parent_id def validates_presence_of_parent_id? true diff --git a/lib/tasks/items.rake b/lib/tasks/items.rake index 8889567da..7d94332ed 100644 --- a/lib/tasks/items.rake +++ b/lib/tasks/items.rake @@ -3,7 +3,7 @@ namespace :items do task :tree_changes => :environment do Item.all.each do |item| - item.position -= 1 + item.position -= item.position > 5 ? 2 : 1 item.parent_ids = ancestors(item) item.rename(:full_name, :path) item.save