Default scope messes with Hightop
synth opened this issue · comments
Peter Philips commented
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
Andrew Kane commented
Hey @synth, this is expected. I'd recommend against using default scopes: https://rails-bestpractices.com/posts/2013/06/15/default_scope-is-evil/