要重写您在问题中得到的 SQL 查询,我认为它应该如下所示(尽管我很难完全可视化您的模型关系,所以这有点猜测):
RagaContextApplicantsSong.
joins(:raga_contest_applicants => [:raga_content_rounds], :contest_cat).
group('raga_contest_rounds.contest_cat_id')
...这样该joins
方法就可以同时处理两个连接以及WHERE
子句,最后是group
调用。
作为更多参考:
如果您将多个关联加入同一个模型,您可以简单地列出它们:
Post.joins(:category, :comments)
Returns all posts that have a category and at least one comment
如果您要加入嵌套表,您可以将它们列为散列:
Post.joins(:comments => :guest)
Returns all comments made by a guest
嵌套关联,多级:
Category.joins(:posts => [{:comments => :guest}, :tags])
Returns all posts with their comments where the post has at least one comment made by a guest
您还可以链接 ActiveRecord 查询接口调用,例如:
Post.joins(:category, :comments)
...produces the same SQL as...
Post.joins(:category).joins(:comments)
如果所有其他方法都失败了,您始终可以将 SQL 片段直接传递到joins
方法中,作为从工作查询到更以 ARQI 为中心的东西的垫脚石
Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
=> SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id