@@ -5,8 +5,13 @@ class WorkshopSearchService
55 def initialize ( params = { } , super_user : false )
66 @params = params
77 @super_user = super_user
8- @workshops = Workshop . all
98 @sort = default_sort
9+ @workshops =
10+ if @sort == "popularity"
11+ Workshop . with_bookmarks_count
12+ else
13+ Workshop . all
14+ end
1015 end
1116
1217 # Main entry point
@@ -196,45 +201,55 @@ def normalize_published_param
196201
197202 def order_by_params
198203 case sort
199- when 'created'
200- # order by year/month desc, then created_at desc, then title asc
204+ when "created"
201205 @workshops = @workshops . order (
202206 Arel . sql ( <<~SQL . squish )
203- CASE WHEN year IS NOT NULL AND month IS NOT NULL THEN 1 ELSE 2 END ASC,
204- year DESC,
205- month DESC,
206- created_at DESC,
207- title ASC
208- SQL
207+ CASE WHEN year IS NOT NULL AND month IS NOT NULL THEN 1 ELSE 2 END ASC,
208+ year DESC,
209+ month DESC,
210+ created_at DESC,
211+ title ASC
212+ SQL
209213 )
210- when ' led'
214+ when " led"
211215 @workshops = @workshops . order ( led_count : :desc , title : :asc )
212- when 'title'
216+ when "popularity"
217+ @workshops = @workshops . order (
218+ Arel . sql ( "bookmarks_count DESC, title ASC" )
219+ )
220+ when "title"
213221 @workshops = @workshops . order ( title : :asc )
214- when ' keywords'
215- # already ordered in filter_by_query
222+ when " keywords"
223+ # already ordered
216224 else
217225 @workshops = @workshops . order ( created_at : :asc , title : :asc )
218226 end
219227 end
220228
229+
221230 # --- Handle distinct + order by FIELD(id, ...) for complex joins ---
222231 def resolve_ids_order
223- return if sort == 'keywords' # ordering is already handled if this is the case
224-
225- # Determine sort columns for select
226- sort_columns = case sort
227- when 'created' then [ :id , :created_at , :year , :month , :title ]
228- when 'led' then [ :id , :led_count , :title ]
229- when 'title' then [ :id , :title ]
230- else [ :id , :title ]
231- end
232-
233- workshop_ids = @workshops
234- . select ( *sort_columns )
235- . order ( sort_columns )
236- . map ( &:id )
237- @workshops = Workshop . where ( id : workshop_ids )
238- . order ( Arel . sql ( "FIELD(id, #{ workshop_ids . join ( ',' ) } )" ) )
232+ return if sort == "keywords"
233+
234+ sort_columns =
235+ case sort
236+ when "created" then [ :id , :created_at , :year , :month , :title ]
237+ when "led" then [ :id , :led_count , :title ]
238+ when "popularity" then [ :id , :bookmarks_count , :title ]
239+ when "title" then [ :id , :title ]
240+ else [ :id , :title ]
241+ end
242+
243+ workshop_ids =
244+ @workshops
245+ . select ( *sort_columns )
246+ . order ( sort_columns )
247+ . map ( &:id )
248+
249+ @workshops =
250+ Workshop
251+ . where ( id : workshop_ids )
252+ . order ( Arel . sql ( "FIELD(id, #{ workshop_ids . join ( ',' ) } )" ) )
239253 end
254+
240255end
0 commit comments