I have a Mail
model with the following schema:
t.string \"mail\"
t.integer \"country\"
t.boolean \"validated\"
t.datetime \"created_at\"
t.d
With Rails 3 you can simplify it further:
Mail.where(validated: true).count(group: :country)
You can order by fields in the group - in this case only :country would be valid:
Mail.where(validated: true)
.order(:country)
.count(group: :country)
You can also order by the count, using "count_all":
Mail.where(validated: true)
.order("count_all desc")
.count(group: :country)
You can also limit the number of groups returned. To do this you must call limit before calling count (because #count
returns ActiveSupport::OrderedHash
):
Mail.where(validated: true)
.order("count_all desc")
.limit(5)
.count(group: :country)
Updated syntax for Rails 4:
Mail.where(validated: true)
.group(:country)
.count