Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord Group by ENUM

I'm using rails 4.1 and the new enum functionality to include an array of enums in my model class e.g:

class Campaign < ActiveRecord::Base    
  enum status: [:pending, :active, :paused, :complete]

end

I want to query campaigns and list a count by status e.g:

Campaign.all.group("status").count

This simple query works fine however returns the integer value of the enum from the DB. Is there an easy rails way to convert this to the string representation?

like image 881
Macros Avatar asked Apr 27 '15 11:04

Macros


2 Answers

Just map numbers to related string values:

Campaign.all.group(:status).count.map { |k, v| [Campaign.statuses.key(k), v] }.to_h
like image 64
Maxim Avatar answered Sep 20 '22 02:09

Maxim


if you want status wise count

campaigns = Campaign.all.group(:status).count

@campaigns = Campaign.statuses.map { |k, v| [k , campaigns[v] || 0] }

it will give output like

{"pending"=>0, "active"=>1, "paused"=>0, "complete"=>0}

like image 22
sonal save Avatar answered Sep 22 '22 02:09

sonal save