如何使用的has_many assocations零号的所有记录找到? [英] How to find all records with zero number of has_many assocations?
问题描述
让我们假设你有问题
模型如下的has_many
的关联:(例如从的这个插件)
Let's say you have Question
model with following has_many
association:(example taken from this plugin)
has_many :comment_threads,
:class_name => "Comment",
:as => :commentable,
:dependent => :destroy
我将如何定义一个范围或一个类的方法返回一个没有相关评论吗?
How would I define a scope or a class method that returns questions that has no associated comments?
基本上我想要 Question.unanswered
返回所有问题的零意见。
Basically I want Question.unanswered
to return all questions with zero comments.
推荐答案
我觉得有办法 counter_cache
是更好和更快,但您可以创建你想要这样的范围(您可能需要一些调整,如果我猜的表或列名称错误):
I think approach with counter_cache
is nicer and faster, but you can create the scope you want like that (you might need some adjustments if I guessed tables or columns names wrong):
scope :unanswered,
joins('LEFT OUTER JOIN comments ON comments.commentable_id = questions.id').
where('comments.id IS NULL')
使用 LEFT OUTER JOIN
生成连接表,其中一个未加注释的问题,意见表中的所有列设置为 NULL
。这些正是我们需要的,所以我们用它们进行过滤的行其中,
。
Using LEFT OUTER JOIN
generates joined table where for an uncommented question all columns of comments table are set to NULL
. These are exactly the rows we need so we filter them using where
.
这篇关于如何使用的has_many assocations零号的所有记录找到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!