Building a subquery with ARel in Rails3
- by Christopher
I am trying to build this query in ARel:
SELECT FLOOR(AVG(num)) FROM (
SELECT COUNT(attendees.id) AS num, meetings.club_id FROM `meetings` INNER JOIN `attendees` ON `attendees`.`meeting_id` = `meetings`.`id` WHERE (`meetings`.club_id = 1) GROUP BY meetings.id) tmp
GROUP BY tmp.club_id
It returns the average number of attendees per meeting, per club. (a club has many meetings and a meeting has many attendees)
So far I have (declared in class Club < ActiveRecord::Base):
num_attendees = meetings.select("COUNT(attendees.id) AS num").joins(:attendees).group('meetings.id')
Arel::Table.new('tmp', self.class.arel_engine).from(num_attendees).project('FLOOR(AVG(num))').group('tmp.club_id').to_sql
but, I am getting the error:
undefined method `visit_ActiveRecord_Relation' for #<Arel::Visitors::MySQL:0x9b42180>
The documentation for generating non trivial ARel queries is a bit hard to come by. I have been using http://rdoc.info/github/rails/arel/master/frames Am I approaching this incorrectly? Or am I a few methods away from a solution?