Skip to content

Commit ba9117d

Browse files
I have added the before_destroy callback to the Crop model to destroy all CropCompanion records where the crop is crop_b. (#4266)
I have added a new test to `spec/models/crop_spec.rb` to verify that deleting a crop also destroys the associated `CropCompanion` records. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
1 parent 474f09e commit ba9117d

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

app/models/crop.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,14 @@ def all_companions
165165
(companions + parent.companions).uniq
166166
end
167167

168+
before_destroy :destroy_reverse_companionships
169+
168170
private
169171

172+
def destroy_reverse_companionships
173+
CropCompanion.where(crop_b: self).destroy_all
174+
end
175+
170176
def count_uses_of_property(col_name)
171177
plantings.unscoped
172178
.where(crop_id: id)

spec/models/crop_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,20 @@
544544
end
545545
end
546546

547+
context "destroying a crop" do
548+
let!(:crop_a) { FactoryBot.create(:crop) }
549+
let!(:crop_b) { FactoryBot.create(:crop) }
550+
551+
before do
552+
CropCompanion.create(crop_a: crop_a, crop_b: crop_b)
553+
CropCompanion.create(crop_a: crop_b, crop_b: crop_a)
554+
end
555+
556+
it "destroys companion links" do
557+
expect { crop_a.destroy }.to change { CropCompanion.count }.from(2).to(0)
558+
end
559+
end
560+
547561
context "crop rejections" do
548562
let!(:rejected_reason) do
549563
FactoryBot.create(:crop, name: 'tomato',

0 commit comments

Comments
 (0)