REFACTOR: improve Notification.ensure_consistency SQL query readability

This commit is contained in:
Régis Hanol 2017-04-24 22:51:09 +02:00
parent 301dd139ae
commit 8fe0bbb238

View File

@ -19,14 +19,20 @@ class Notification < ActiveRecord::Base
after_commit :refresh_notification_count, on: [:create, :update]
def self.ensure_consistency!
Notification.exec_sql("
DELETE FROM Notifications n WHERE notification_type = :id AND
NOT EXISTS(
SELECT 1 FROM posts p
JOIN topics t ON t.id = p.topic_id
WHERE p.deleted_at is null AND t.deleted_at IS NULL
AND p.post_number = n.post_number AND t.id = n.topic_id
)" , id: Notification.types[:private_message])
Notification.exec_sql <<-SQL
DELETE
FROM notifications n
WHERE notification_type = #{Notification.types[:private_message]}
AND NOT EXISTS (
SELECT 1
FROM posts p
JOIN topics t ON t.id = p.topic_id
WHERE p.deleted_at IS NULL
AND t.deleted_at IS NULL
AND p.post_number = n.post_number
AND t.id = n.topic_id
)
SQL
end
def self.types
@ -66,13 +72,12 @@ class Notification < ActiveRecord::Base
end
def self.read(user, notification_ids)
count = Notification.where(user_id: user.id,
id: notification_ids,
read: false).update_all(read: true)
count = Notification.where(user_id: user.id)
.where(id: notification_ids)
.where(read: false)
.update_all(read: true)
if count > 0
user.publish_notifications_state
end
user.publish_notifications_state if count > 0
end
def self.interesting_after(min_date)