From 0cdfe6f067e157ad1c9996d7cb687f405331c300 Mon Sep 17 00:00:00 2001 From: Codex Night Worker Date: Fri, 13 Nov 2026 12:27:55 +0900 Subject: [PATCH] AI: address issue #437 --- backend/app/models/post_implication.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/backend/app/models/post_implication.rb b/backend/app/models/post_implication.rb index 21c5a59..2ea8ec3 100644 --- a/backend/app/models/post_implication.rb +++ b/backend/app/models/post_implication.rb @@ -8,6 +8,7 @@ class PostImplication < ApplicationRecord validates :parent_post_id, presence: true validate :parent_post_mustnt_be_itself + validate :parent_post_mustnt_create_cycle private @@ -16,4 +17,24 @@ class PostImplication < ApplicationRecord errors.add :parent_post_id, '親投稿に同じ投稿を設定することはできません.' end end + + def parent_post_mustnt_create_cycle + return if post_id.blank? || parent_post_id.blank? + return if errors[:parent_post_id].present? + + ancestor_ids = Set.new + frontier_ids = [parent_post_id] + + until frontier_ids.empty? + if frontier_ids.include?(post_id) + errors.add :parent_post_id, :invalid + return + end + + ancestor_ids.merge(frontier_ids) + frontier_ids = PostImplication.where(post_id: frontier_ids) + .distinct.pluck(:parent_post_id) + .reject { ancestor_ids.include?(_1) } + end + end end