Post#expunge!: run callbacks when reparenting children.
* Set parent IDs with `update` instead of `update_column` / `update_all` when reparenting children. This fixes it so that new post versions are saved and the has_children flag is set on the new parent. * Slightly simplify logic of update_children_on_destroy: the single child case is subsumed by the multi-child case.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user