Fix bugs for shift_to and change items.rake for the missing position in db

This commit is contained in:
Christophe Vilayphiou 2012-05-11 17:56:26 +08:00
parent 6a443f0976
commit 17b486f9e9
3 changed files with 20 additions and 1 deletions

View File

@ -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

View File

@ -36,12 +36,29 @@ class Item
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
def rebuild_path
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

View File

@ -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