Changing count to size to prevent unneeded DB query on @project_notifications
@digitalmoksha @smcgivern @mdelaossa #34296 (closed)
Need to replace count
with size
.
https://gitlab.com/gitlab-org/gitlab/blob/master/app/views/profiles/notifications/show.html.haml#L47
= _('Projects (%{count})') % { count: @project_notifications.count }
[17] pry(main)> @project_notifications.class
=> NotificationSetting::ActiveRecord_AssociationRelation
Calling count
will trigger a DB call on ActiveRecord_AssociationRelation
.
@project_notifications.count
(3.9ms) SELECT COUNT(DISTINCT "notification_settings"."id") FROM "notification_settings" LEFT OUTER JOIN "projects" ON "projects"."id" = "notification_settings"."source_id" LEFT OUTER JOIN "routes" ON "routes"."source_id" = "projects"."id" AND "routes"."source_type" = $1 WHERE "notification_settings"."user_id" = $2 AND "notification_settings"."source_type" = $3 AND "projects"."id" IS NOT NULL AND "projects"."pending_delete" != $4 [["source_type", "Project"], ["user_id", 1], ["source_type", "Project"], ["pending_delete", true]]
=> 3
While size
won't since it already knows how many objects exists and it doesn't recalculate it using the DB.
[19] pry(main)> @project_notifications.size
=> 3
size
will run a DB query or calculate from memory automatically.
https://apidock.com/rails/ActiveRecord/Associations/AssociationCollection/size
Edited by Ohad Dahan