带连接的Rails范围

时间:2016-01-11 13:39:25

标签: ruby-on-rails ruby

我有两个模型,postcomment

我需要名为post的{​​{1}}范围,该范围定义为该帖子的评论存在。我确信这很简单,但我的想法是空白的!

所以我需要能够做类似

的事情
in_use

但不知道如何在范围内执行此操作?

2 个答案:

答案 0 :(得分:2)

最佳优化方式:

scope :in_use, -> { where("exists (select * from comments where post_id=posts.id)") }

在任何rdbms中都可以很好地优化,并且如果查询被链接,它将进行优化。

答案 1 :(得分:1)

scope :in_use, -> { includes(:comments).where("post.comments <> ''") }