forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sidebar_section_links_updater.rb
51 lines (43 loc) · 1.67 KB
/
sidebar_section_links_updater.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true
class SidebarSectionLinksUpdater
def self.update_category_section_links(user, category_ids:)
if category_ids.blank?
delete_section_links(user: user, linkable_type: "Category")
else
category_ids = Category.where(id: category_ids).pluck(:id)
update_section_links(user: user, linkable_type: "Category", new_linkable_ids: category_ids)
end
end
def self.update_tag_section_links(user, tag_ids:)
if tag_ids.blank?
delete_section_links(user: user, linkable_type: "Tag")
else
update_section_links(user: user, linkable_type: "Tag", new_linkable_ids: tag_ids)
end
end
def self.delete_section_links(user:, linkable_type:)
SidebarSectionLink.where(user: user, linkable_type: linkable_type).delete_all
end
private_class_method :delete_section_links
def self.update_section_links(user:, linkable_type:, new_linkable_ids:)
SidebarSectionLink.transaction do
existing_linkable_ids =
SidebarSectionLink.where(user: user, linkable_type: linkable_type).pluck(:linkable_id)
to_delete = existing_linkable_ids - new_linkable_ids
to_insert = new_linkable_ids - existing_linkable_ids
to_insert_attributes =
to_insert.map do |linkable_id|
{ linkable_type: linkable_type, linkable_id: linkable_id, user_id: user.id }
end
if to_delete.present?
SidebarSectionLink.where(
user: user,
linkable_type: linkable_type,
linkable_id: to_delete,
).delete_all
end
SidebarSectionLink.insert_all(to_insert_attributes) if to_insert_attributes.present?
end
end
private_class_method :update_section_links
end