0

I have a Ticket.rb model, and School.rb model.

Ticket belongs_to School

School has_many Tickets

How can I use ActiveRecord to find out total .count of how many Tickets each School has?

I'm aware that Ticket.where(:school_id => -insert School ID here-).count will give me the individual count of each school but I'm using this to populate the data into a graph so I really need something more like School.tickets.count.

Is this possible without messing up my associations?

Thanks all..

Devin
  • 1,011
  • 2
  • 14
  • 30

2 Answers2

3
Ticket.group(:school_id).count

This will give you the count of tickets for each school id with key as the school_id and the value as the ticket count

If you want to group by a different attribute on School, then

Ticket.joins(:school).group("schools.name").count

Eg output:

{3 => 10, 4 => 30}
usha
  • 28,973
  • 5
  • 72
  • 93
  • Thank you. What if my School model had a 'name' column that I'd rather have show instead of the ID? i.e. {School 1 => 10, School 2 => 30} – Devin Nov 25 '13 at 22:18
0

If you have a specific School instance (such as @school), you can use @school.tickets.count.

For better performance, you can use the group method in your controller outlined here.

So in your controller:

def someaction
  @school_tickets = Ticket.group(:school_id)
end

and in your view you can loop through the @school_tickets such as:

@school_tickets.each do |school_ticket|
  school_ticket.count
end
AbM
  • 7,326
  • 2
  • 25
  • 28
  • 1
    There is no `group_by` method on ActiveRecord class. Did you mean `Ticket.all.group_by`? Because `group_by` is available only for arrays – usha Nov 25 '13 at 22:13