From 0f6baaf4ba2a9f6d18c8550bda310fae3ef35617 Mon Sep 17 00:00:00 2001 From: rhymes Date: Fri, 14 Aug 2020 15:29:08 +0200 Subject: [PATCH] [deploy] Remove orphaned DisplayAdEvent rows (#9765) * Remove orphaned DisplayAdEvent rows * Add dependent in the has_many relationship between ads and ad events --- app/models/display_ad.rb | 2 +- ...72205_remove_orphaned_display_ad_events.rb | 21 +++++++++++++++++++ spec/models/display_ad_spec.rb | 15 +++++++++---- 3 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 lib/data_update_scripts/20200813072205_remove_orphaned_display_ad_events.rb diff --git a/app/models/display_ad.rb b/app/models/display_ad.rb index fb9a51073..8ec9619ec 100644 --- a/app/models/display_ad.rb +++ b/app/models/display_ad.rb @@ -1,6 +1,6 @@ class DisplayAd < ApplicationRecord belongs_to :organization - has_many :display_ad_events + has_many :display_ad_events, dependent: :destroy validates :organization_id, presence: true validates :placement_area, presence: true, diff --git a/lib/data_update_scripts/20200813072205_remove_orphaned_display_ad_events.rb b/lib/data_update_scripts/20200813072205_remove_orphaned_display_ad_events.rb new file mode 100644 index 000000000..b2c10b793 --- /dev/null +++ b/lib/data_update_scripts/20200813072205_remove_orphaned_display_ad_events.rb @@ -0,0 +1,21 @@ +module DataUpdateScripts + class RemoveOrphanedDisplayAdEvents + def run + # Delete all DisplayAdEvents belonging to DisplayAds that don't exist anymore + ActiveRecord::Base.connection.execute( + <<~SQL, + DELETE FROM display_ad_events + WHERE display_ad_id NOT IN (SELECT id FROM display_ads); + SQL + ) + + # Delete all DisplayAdEvents belonging to Users that don't exist anymore + ActiveRecord::Base.connection.execute( + <<~SQL, + DELETE FROM display_ad_events + WHERE user_id NOT IN (SELECT id FROM users); + SQL + ) + end + end +end diff --git a/spec/models/display_ad_spec.rb b/spec/models/display_ad_spec.rb index 5f418e3be..df275405a 100644 --- a/spec/models/display_ad_spec.rb +++ b/spec/models/display_ad_spec.rb @@ -4,11 +4,18 @@ RSpec.describe DisplayAd, type: :model do let(:organization) { create(:organization) } let(:display_ad) { create(:display_ad, organization_id: organization.id) } - it { is_expected.to validate_presence_of(:organization_id) } - it { is_expected.to validate_presence_of(:placement_area) } - it { is_expected.to validate_presence_of(:body_markdown) } - describe "validations" do + describe "builtin validations" do + subject { display_ad } + + it { is_expected.to belong_to(:organization) } + it { is_expected.to have_many(:display_ad_events).dependent(:destroy) } + + it { is_expected.to validate_presence_of(:organization_id) } + it { is_expected.to validate_presence_of(:placement_area) } + it { is_expected.to validate_presence_of(:body_markdown) } + end + it "allows sidebar_right" do display_ad.placement_area = "sidebar_right" expect(display_ad).to be_valid