Fix destroying of users in relation to notifications

This commit is contained in:
Luka Murn 2016-11-15 15:56:32 +01:00
parent 04749c3b2c
commit eb4d031b79
2 changed files with 25 additions and 1 deletions

View file

@ -1,5 +1,5 @@
class Notification < ActiveRecord::Base
has_many :user_notifications, inverse_of: :notification
has_many :user_notifications, inverse_of: :notification, dependent: :destroy
has_many :users, through: :user_notifications
belongs_to :generator_user, class_name: 'User'

View file

@ -92,11 +92,14 @@ class User < ActiveRecord::Base
has_many :restored_protocols, class_name: 'Protocol', foreign_key: 'restored_by_id', inverse_of: :restored_by
has_many :user_notifications, inverse_of: :user
has_many :notifications, through: :user_notifications
# If other errors besides parameter "avatar" exist,
# they will propagate to "avatar" also, so remove them
# and put all other (more specific ones) in it
after_validation :filter_paperclip_errors
before_destroy :destroy_notifications
def name
full_name
end
@ -251,4 +254,25 @@ class User < ActiveRecord::Base
errors.add(:time_zone)
end
end
private
def destroy_notifications
# Find all notifications where user is the only reference
# on the notification, and destroy all such notifications
# (user_notifications are destroyed when notification is
# destroyed). We try to do this efficiently (hence in_groups_of).
nids_all = notifications.pluck(:id)
nids_all.in_groups_of(1000, false) do |nids|
Notification
.where(id: nids)
.joins(:user_notifications)
.group('notifications.id')
.having('count(notification_id) <= 1')
.destroy_all
end
# Now, simply destroy all user notification relations left
user_notifications.destroy_all
end
end