Skip to content

Commit ddac753

Browse files
committed
models: add eager-loadable host association to Workshop
- Add has_one :workshop_host with inverse_of for proper association caching - Add has_one :host through :workshop_host for eager loading - Replace inefficient raw SQL host method with association-based implementation This eliminates N+1 queries when loading workshop hosts on the events index page.
1 parent 506f57e commit ddac753

1 file changed

Lines changed: 5 additions & 12 deletions

File tree

app/models/workshop.rb

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ class Workshop < ApplicationRecord
1010
has_many :invitations, class_name: 'WorkshopInvitation'
1111
has_many :workshop_sponsors
1212
has_many :sponsors, through: :workshop_sponsors
13+
has_one :workshop_host, -> { where(workshop_sponsors: { host: true }) },
14+
class_name: 'WorkshopSponsor',
15+
inverse_of: :workshop
16+
has_one :host, through: :workshop_host, source: :sponsor
1317
has_many :organisers, -> { where('permissions.name' => 'organiser') }, through: :permissions, source: :members
1418
has_many :feedbacks
1519

@@ -31,18 +35,7 @@ class Workshop < ApplicationRecord
3135
before_validation :set_opens_at
3236

3337
def host
34-
sql = <<~SQL
35-
SELECT sponsors.*
36-
FROM sponsors
37-
LEFT JOIN workshop_sponsors ON workshop_sponsors.sponsor_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
38+
workshop_host&.sponsor
4639
end
4740

4841
def waiting_list

0 commit comments

Comments
 (0)