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