[英]getting .count of associated model
I have a Ticket.rb model, and School.rb model. 我有一个Ticket.rb模型和School.rb模型。
Ticket belongs_to
School 门票belongs_to
学校
School has_many
Tickets 学校has_many
门票
How can I use ActiveRecord to find out total .count
of how many Tickets each School has? 我如何使用ActiveRecord找出总.count
有多少门票每个学校都有的?
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
. 我知道Ticket.where(:school_id => -insert School ID here-).count
会给我每所学校的个人计数,但是我正在使用它来将数据填充到图形中,所以我真的需要更多像School.tickets.count
一样。
Is this possible without messing up my associations? 这有可能在不弄乱我的协会的情况下吗?
Thanks all.. 谢谢大家
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 这将为您提供每个学校ID的票数,其中键为school_id,值为票数
If you want to group by a different attribute on School, then 如果要在School上按其他属性分组,则
Ticket.joins(:school).group("schools.name").count
Eg output: 例如输出:
{3 => 10, 4 => 30}
If you have a specific School instance (such as @school
), you can use @school.tickets.count
. 如果您有特定的School实例(例如@school
),则可以使用@school.tickets.count
。
For better performance, you can use the group
method in your controller outlined here . 为了获得更好的性能,您可以在此处概述的控制器中使用group
方法。
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
例如:
@school_tickets.each do |school_ticket|
school_ticket.count
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.