Skip to content

Commit 53c76bf

Browse files
committed
fix: workshop model host n+1 query
Use a sql statement with join rather than active record
1 parent 0ed3699 commit 53c76bf

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

app/models/workshop.rb

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,19 @@ class Workshop < ApplicationRecord
3030
before_validation :set_date_and_time, :set_end_date_and_time, if: proc { |model| model.chapter_id.present? }
3131
before_validation :set_opens_at
3232

33-
def workshop_sponsors_with_host_true
34-
workshop_sponsors.where(host: true)
35-
end
36-
3733
def host
38-
workshop_sponsors_with_host_true.first&.sponsor
34+
sql = <<~SQL
35+
SELECT sponsors.*
36+
FROM sponsors
37+
LEFT JOIN workshop_sponsors ON workshop_sponsors.workshop_id = sponsors.id
38+
WHERE workshop_sponsors.workshop_id = ?
39+
AND workshop_sponsors.host = TRUE
40+
AND sponsors.id = workshop_sponsors.sponsor_id
41+
ORDER BY sponsors.updated_at DESC, workshop_sponsors.id ASC
42+
LIMIT 1
43+
SQL
44+
45+
Sponsor.find_by_sql([sql, id]).first
3946
end
4047

4148
def waiting_list

0 commit comments

Comments
 (0)