Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

destroy relations upon work package destruction

ulferts6a27c7c9383f
diff --git a/app/models/work_package.rb b/app/models/work_package.rb
index 76e36bf58a3..83580a1ca71 100644
--- a/app/models/work_package.rb
+++ b/app/models/work_package.rb
@@ -227,19 +227,11 @@ class WorkPackage < ApplicationRecord
.exists?
end
- def relations
- Relation.of_work_package(self)
- end
-
def visible_relations(user)
relations
.visible(user)
end
- def relation(id)
- Relation.of_work_package(self).find(id)
- end
-
def add_time_entry(attributes = {})
attributes.reverse_merge!(
project:,
diff --git a/app/models/work_packages/relations.rb b/app/models/work_packages/relations.rb
index e61e8d55fda..8fd825996d9 100644
--- a/app/models/work_packages/relations.rb
+++ b/app/models/work_packages/relations.rb
@@ -28,6 +28,17 @@ module WorkPackages::Relations
extend ActiveSupport::Concern
included do
+ # All relations of the work package in both directions.
+ # Mostly used to have the relations destroyed upon destruction of the work package.
+ # rubocop:disable Rails:InverseOf
+ has_many :relations,
+ ->(work_package) {
+ unscope(:where)
+ .of_work_package(work_package)
+ },
+ dependent: :destroy
+ # rubocop:enable Rails:InverseOf
+
# Relations where the current work package follows another one.
# In this case,
# * from is self.id
diff --git a/spec/models/work_package/work_package_relations_spec.rb b/spec/models/work_package/work_package_relations_spec.rb
index 3f039bc126b..69dfda4d7b3 100644
--- a/spec/models/work_package/work_package_relations_spec.rb
+++ b/spec/models/work_package/work_package_relations_spec.rb
@@ -100,8 +100,8 @@ describe WorkPackage, type: :model do
end
it 'only duplicates are closed' do
- expect(dup_1.closed?).to be_truthy
- expect(dup_2.closed?).to be_truthy
+ expect(dup_1).to be_closed
+ expect(dup_2).to be_closed
end
end
@@ -227,4 +227,31 @@ describe WorkPackage, type: :model do
end
end
end
+
+ describe '#destroy' do
+ let(:work_package) { create(:work_package) }
+ let(:other_work_package) { create(:work_package) }
+
+ context 'for a work package with a relation as to' do
+ let!(:to_relation) { create(:follows_relation, from: other_work_package, to: work_package) }
+
+ it 'removes the relation as well as the work package' do
+ work_package.destroy
+
+ expect(Relation)
+ .not_to exist(id: to_relation.id)
+ end
+ end
+
+ context 'for a work package with a relation as from' do
+ let!(:from_relation) { create(:follows_relation, to: other_work_package, from: work_package) }
+
+ it 'removes the relation as well as the work package' do
+ work_package.destroy
+
+ expect(Relation)
+ .not_to exist(id: from_relation.id)
+ end
+ end
+ end
end