diff --git a/app/models/post.rb b/app/models/post.rb index 04f974c82..6c82a89ce 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1314,17 +1314,14 @@ class Post < ApplicationRecord end def update_children_on_destroy - if children.size == 0 - # do nothing - elsif children.size == 1 - children.first.update_column(:parent_id, nil) - else - cached_children = children - eldest = cached_children[0] - siblings = cached_children[1..-1] - eldest.update_column(:parent_id, nil) - Post.where(:id => siblings.map(&:id)).update_all(:parent_id => eldest.id) - end + return unless children.present? + + eldest = children[0] + siblings = children[1..-1] + + eldest.update(parent_id: nil) + Post.where(id: siblings).find_each { |p| p.update(parent_id: eldest.id) } + # Post.where(id: siblings).update(parent_id: eldest.id) # XXX rails 5 end def update_parent_on_save diff --git a/test/unit/post_test.rb b/test/unit/post_test.rb index d0b760fb2..4b5496136 100644 --- a/test/unit/post_test.rb +++ b/test/unit/post_test.rb @@ -254,18 +254,39 @@ class PostTest < ActiveSupport::TestCase end context "two or more children" do + setup do + # ensure initial post versions won't be merged. + travel_to(1.day.ago) do + @p1 = FactoryGirl.create(:post) + @c1 = FactoryGirl.create(:post, :parent_id => @p1.id) + @c2 = FactoryGirl.create(:post, :parent_id => @p1.id) + @c3 = FactoryGirl.create(:post, :parent_id => @p1.id) + end + end + should "reparent all children to the first child" do - p1 = FactoryGirl.create(:post) - c1 = FactoryGirl.create(:post, :parent_id => p1.id) - c2 = FactoryGirl.create(:post, :parent_id => p1.id) - c3 = FactoryGirl.create(:post, :parent_id => p1.id) - p1.expunge! - c1.reload - c2.reload - c3.reload - assert_nil(c1.parent_id) - assert_equal(c1.id, c2.parent_id) - assert_equal(c1.id, c3.parent_id) + @p1.expunge! + @c1.reload + @c2.reload + @c3.reload + + assert_nil(@c1.parent_id) + assert_equal(@c1.id, @c2.parent_id) + assert_equal(@c1.id, @c3.parent_id) + end + + should "save a post version record for each child" do + assert_difference(["@c1.versions.count", "@c2.versions.count", "@c3.versions.count"]) do + @p1.expunge! + @c1.reload + @c2.reload + @c3.reload + end + end + + should "set the has_children flag on the new parent" do + @p1.expunge! + assert_equal(true, @c1.reload.has_children?) end end end