ankane / hightop

A nice shortcut for group count queries

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Default scope messes with Hightop

synth opened this issue · comments

Given:

[24] pry(main)> Recognition.top(:sender_company_id, 10)
   (144.6ms)  SELECT  COUNT(*) AS count_all, sender_company_id AS sender_company_id FROM `recognitions`  WHERE `recognitions`.`deleted_at` IS NULL AND (sender_company_id IS NOT NULL) GROUP BY `recognitions`.`sender_company_id`  ORDER BY recognitions.created_at DESC, recognitions.id DESC, count_all DESC, sender_company_id LIMIT 10
=> {8132=>1, 4379=>2, 8126=>3, 1665=>1, 8122=>1, 7760=>11, 5305=>1, 8105=>3, 8104=>2, 6417=>1}

[25] pry(main)> Recognition.top(:sender_company_id, min: 1000)
   (148.7ms)  SELECT COUNT(*) AS count_all, sender_company_id AS sender_company_id FROM `recognitions`  WHERE `recognitions`.`deleted_at` IS NULL AND (sender_company_id IS NOT NULL) GROUP BY `recognitions`.`sender_company_id` HAVING COUNT(*) >= 1000  ORDER BY recognitions.created_at DESC, recognitions.id DESC, count_all DESC, sender_company_id
=> {3552=>3775,
 3744=>1952,
 5790=>4211,
 4415=>10285,
 3724=>1032,
 1591=>13545,
 3000=>2289,
 2967=>2385,
 2308=>1320,
 2146=>23427,
 1936=>1899,
 1512=>2494,
 323=>1506,
 1=>9577}

You can see in the first call which uses the limit syntax, I do not get the expected results because of default scope which adds a default order clause.

Should hightop ignore default scopes, or should it issue warning if they exist?

Recognition.unscoped.top(:sender_company_id, 10) works as expected

Hey @synth, this is expected. I'd recommend against using default scopes: https://rails-bestpractices.com/posts/2013/06/15/default_scope-is-evil/