繁体   English   中英

包括不允许外连接和子表的计数

[英]Includes not allowing outer join and count on child table

class Course < ActiveRecord::Base
  has_many :registrations

  delegate :count, to: :registrations, prefix: true
end

class Registration < ActiveRecord::Base
  belongs_to :course
end

在我的课程索引视图中,我显示了每条记录的注册计数。 这是什么最佳做法? 使用包含(:registrations)和委托的registrations_count方法看起来比在主查询中执行数据库计数要慢(在控制台中)。

我想显示所有记录,所以我不能使用INNER join()。 使用includes()如下所示给出错误PG::GroupingError: ERROR: column "registrations.id" must appear in the GROUP BY clause or be used in an aggregate function我尝试添加一个where子句:注册到此但它仍然误:

Course.includes(:registrations).group("courses.id").select("courses.*, COUNT(registrations.id) as registrations_count")

是否必须如下指定外连接?

Course.joins('LEFT OUTER JOIN registrations ON registrations.course_id = courses.id').select('courses.*, COUNT(registrations.id) as registrations_count').group('courses.id')

这最后一个查询确实有效,但感觉我正在做的应该是相当标准的,所以我想确保我采取正确的方法。

在我的课程索引视图中,我显示了每条记录的注册计数。 这是什么最佳做法?

counter_caching是计算association对象的最佳选择。 Rails中的计数器缓存只是跟踪关联模型数量的附加列。

你必须这样做

belongs_to :course , counter_cache: true

然后你就可以做到这一点

@course.registrations_count

RailsCast中了解更多信息

看起来你错过了includesjoins之间的区别, 在这里学习

对我来说这很好。

Course.joins('LEFT OUTER JOIN registrations ON registrations.course_id = courses.id').select('courses.*, COUNT(registrations.id) as registrations_count').group('courses.id')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM