Bitwise
Bitwise

Reputation: 8461

Active Record - Charting how many people in a group?

I'm using Chartkick in my RoR app and I'm trying to create a pie chart that displays all the People that are in each Group. My Group and Person model are both HABTM. Right now the chart is working and only displaying number of groups(screenshot and code below) if someone knows how to grab the number of people in each group using active record I'd love it!

here is my code

<%= pie_chart Group.group(:name).count %>

Here is a screenshot

enter image description here

here is my Schema

  create_table "people", force: :cascade do |t|
t.string   "phone_number"
t.datetime "created_at",                  null: false
t.datetime "updated_at",                  null: false
t.boolean  "subscribed",   default: true, null: false
t.string   "city"
t.string   "state"
t.string   "zip"
t.string   "country"
 end

 create_table "groups", force: :cascade do |t|
t.string   "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

 create_table "groups_people", id: false, force: :cascade do |t|
t.integer "group_id",  null: false
t.integer "person_id", null: false
end

here is the person model

class Person < ActiveRecord::Base
has_many :deliveries
has_and_belongs_to_many :groups

here is group model

class Group < ActiveRecord::Base
 has_and_belongs_to_many :people
 has_and_belongs_to_many :messages
end

Upvotes: 1

Views: 85

Answers (1)

Ilya
Ilya

Reputation: 13477

<%= pie_chart Group.includes(:people).all.map {|g| [g.name, g.people.size] }.to_h %>

By the way, it will better to move this logic into model body.

Upvotes: 1

Related Questions