0

With the following

@items.group(:nature_id).count(:nature_id)

one obtains a hash of results

{4=>1, 8=>1, 14=>2, 27=>1, 32=>1, 33=>1, 36=>1, 41=>2, 44=>1, 63=>1, 64=>4, 69=>1, 130=>7, 131=>3,[...]}

How can this result be sorted by the count value in decreasing order of said value & the result limited to 100 records?

Jerome
  • 5,583
  • 3
  • 33
  • 76

1 Answers1

1

Try the below:

@items.group(:nature_id).order('COUNT(nature_id) DESC').limit(100).count(:nature_id)

order('COUNT(nature_id) DESC') - Will order the result by the count

Also, syntaxically, this non-attribute arguments will be disallowed in Rails 6.0.

According this post COUNT(nature_id) DESC doesn't going include any user input for SQL injection we need to explicitly bypass it with the below:

@items.group(:nature_id).order(Arel.sql('COUNT(nature_id) DESC')).limit(100).count(:nature_id)
user11350468
  • 1,357
  • 1
  • 6
  • 22
  • That is returning the same hash as that in the question... Also, syntaxically, this non-attribute arguments will be disallowed in Rails 6.0. – Jerome May 20 '20 at 14:27
  • Actually, examining the generated sql, @items was already ordered in a previous statement, this one simply regenerated the ordering filter. The syntax that got it through required removal of the order in upstream command then `@items.group(:nature_id).order(count_nature_id: :desc).limit(100).count(:nature_id)` – Jerome May 20 '20 at 14:36