问题
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?
回答1:
When you build conplicated, full queries in Arel, there's no way to turn that into a list of proper ActiveRecord objects. Only the predicates in Arel, the things you can specify inside a .where() function, can be used.
These advantages, however, are succinctly wrapped up into the meta_where gem:
http://metautonomo.us/projects/metawhere/
Take their advice about adding
MetaWhere.operator_overload!
to your
config/initializers/meta_where.rb
so that you can do things with the '[]' function added to symbol:
Attendee.select(:count[:id].as('person_count')).group(:id)
回答2:
This is how I accomplished it without using Arel methods:
sql = 'SELECT FLOOR(AVG(num)) AS avg FROM ('
sql << meetings.select("COUNT(attendees.id) AS num, meetings.club_id").joins(:attendees).group('meetings.id').to_sql
sql << ') AS tmp GROUP BY tmp.club_id'
connection.select_value(sql, 'avg').to_i
来源:https://stackoverflow.com/questions/4542684/building-a-subquery-with-arel-in-rails3