我有两个模型,post
和comment
我需要名为post
的{{1}}范围,该范围定义为该帖子的评论存在。我确信这很简单,但我的想法是空白的!
所以我需要能够做类似
的事情in_use
但不知道如何在范围内执行此操作?
答案 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 <> ''") }