[deploy] Remove orphaned DisplayAdEvent rows (#9765)

* Remove orphaned DisplayAdEvent rows

* Add dependent in the has_many relationship between ads and ad events
This commit is contained in:
rhymes 2020-08-14 15:29:08 +02:00 committed by GitHub
parent e9c513fb3f
commit 0f6baaf4ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 5 deletions

View file

@ -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,

View file

@ -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

View file

@ -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