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?
Just map numbers to related string values:
Campaign.all.group(:status).count.map { |k, v| [Campaign.statuses.key(k), v] }.to_h
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With