Skip to content

Commit 849c33f

Browse files
committed
refactor user active/inactive scopes for performance
1 parent 8a39f58 commit 849c33f

File tree

1 file changed

+12
-42
lines changed

1 file changed

+12
-42
lines changed

app/models/user.rb

Lines changed: 12 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -328,57 +328,27 @@ def owned = where(owner: proxy_association.owner)
328328
scope :admins, -> { with_role(:admin) }
329329
scope :users, -> { with_role(:user) }
330330
scope :banned, -> { where.not(banned_at: nil) }
331+
scope :unbanned, -> { where(banned_at: nil) }
331332
scope :active, -> (t = 90.days.ago) {
332-
# include any users newer than :t or with an active license
333-
where('users.created_at >= ?', t)
334-
.where(banned_at: nil)
333+
users = License.distinct
334+
.reselect(arel_table[Arel.star])
335+
.joins(:users)
336+
.active
337+
.reorder(nil)
338+
339+
from(users, table_name)
340+
.unbanned
335341
.union(
336-
joins(:licenses)
337-
.where(banned_at: nil)
338-
.where(<<~SQL.squish, t:)
339-
licenses.created_at >= :t OR
340-
(licenses.last_validated_at IS NOT NULL AND licenses.last_validated_at >= :t) OR
341-
(licenses.last_check_out_at IS NOT NULL AND licenses.last_check_out_at >= :t) OR
342-
(licenses.last_check_in_at IS NOT NULL AND licenses.last_check_in_at >= :t)
343-
SQL
342+
where('users.created_at >= ?', t).unbanned,
344343
)
345344
.reorder(
346345
created_at: DEFAULT_SORT_ORDER,
347346
)
348347
}
349348
scope :inactive, -> (t = 90.days.ago) {
350-
# include users older than :t with no licenses
351349
where('users.created_at < ?', t)
352-
.where.missing(:licenses)
353-
.where(banned_at: nil)
354-
.union(
355-
# include users older than :t with inactive licenses
356-
joins(:licenses)
357-
.where('users.created_at < ?', t)
358-
.where(banned_at: nil)
359-
.where(<<~SQL.squish, t:)
360-
licenses.created_at < :t AND
361-
(licenses.last_validated_at IS NULL OR licenses.last_validated_at < :t) AND
362-
(licenses.last_check_out_at IS NULL OR licenses.last_check_out_at < :t) AND
363-
(licenses.last_check_in_at IS NULL OR licenses.last_check_in_at < :t)
364-
SQL
365-
)
366-
# exclude users older than :t with active licenses
367-
.where.not(
368-
id: joins(:licenses)
369-
.reorder(nil)
370-
.where('users.created_at < ?', t)
371-
.where(banned_at: nil)
372-
.where(<<~SQL.squish, t:)
373-
licenses.created_at >= :t OR
374-
(licenses.last_validated_at IS NOT NULL AND licenses.last_validated_at >= :t) OR
375-
(licenses.last_check_out_at IS NOT NULL AND licenses.last_check_out_at >= :t) OR
376-
(licenses.last_check_in_at IS NOT NULL AND licenses.last_check_in_at >= :t)
377-
SQL
378-
)
379-
.reorder(
380-
created_at: DEFAULT_SORT_ORDER,
381-
)
350+
.where.not(id: active)
351+
.unbanned
382352
}
383353
scope :assigned, -> (status = true) {
384354
sub_query = License.where('licenses.user_id = users.id').select(1).arel.exists

0 commit comments

Comments
 (0)