Building a subquery with ARel in Rails3

元气小坏坏 提交于 2020-01-06 02:20:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!