Search code examples
ruby-on-railsruby-on-rails-4ruby-on-rails-5rails-postgresql

How to group and count the last N results?


In Rails, you can use:

Model.group(:field).count

to yield something like:

{"a"=>7, "b"=>5, "c"=>3 "d"=>3, "e"=>4}

But how can I count ONLY in the last N lines, not the entire table, with the DATABASE doing the calculations?

Do not work:

Model.limit(100).group(:field).count

limit will limit the hash output keys not the table lines used

Model.last(100).group(:field).count

Last returns a Array and raises an error

I'm using: * Ruby 2.3.3p222 * Rails 4.2.4 * pg 9.5.6


Solution

  • As you mentioned, the limit is being applied on the grouped instances, not the instances themselves. A simple workaround would be:

    Model.where(id: Model.limit(100).select(:id)).group(:field).count