在 Rails3 中使用 ARel 构建子查询
我正在尝试在 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
它返回每个俱乐部每次会议的平均与会者人数。 (一个俱乐部有很多会议,一个会议有很多与会者)
到目前为止,我已经(在类 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
但是,我收到错误:
undefined method `visit_ActiveRecord_Relation' for #<Arel::Visitors::MySQL:0x9b42180>
生成非平凡 ARel 查询的文档有点困难过来。我一直在使用 http://rdoc.info/github/rails/arel/master/frames 我处理这个问题的方法不正确吗?或者我距离解决方案还差一些方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在 Arel 中构建复杂的完整查询时,无法将其转换为正确的 ActiveRecord 对象列表。只能使用 Arel 中的谓词,即您可以在 .where() 函数内指定的内容。
然而,这些优点都简洁地包含在 meta_where gem 中:
的建议,
听取他们关于添加到您
以便您可以使用添加到符号的“[]”函数来执行操作:
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:
Take their advice about adding
to your
so that you can do things with the '[]' function added to symbol:
这就是我在不使用 Arel 方法的情况下完成它的方法:
This is how I accomplished it without using Arel methods: