Rails arel grouping and counting with associations
activerecord, ruby-on-rails, ruby-on-rails-3
Solution
Job.where("status = ?", "Pending").joins(:member).group("member.name").count
Problem
Given I have a Members table : ``` id membername ------------------- 1 Fred 2 Dave 3 Jenny ``` and a Jobs table ``` id member_id status 1 1 Closed 2 2 Pending 3 2 Open 4 3 Pending 5 3 Pending ``` I want to output the total number of Pending jobs by member. So with the above data, I'd like: ``` membername count Dave 1 Jenny 2 ``` I can grab the counts using the group method, eg ``` Job.where("status = ?", "Pending").group(:member_id).count ``` but this doesn't return the names. Just a hash of member_id's and counts. I'm thinking I need to join this result to the members table somehow. I can do this with raw SQL of course, but was wondering if there is a neater arel way of grabbing this data.