问题
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?
Basically I want Question.unanswered
to return all questions with zero comments.
回答1:
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')
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
.
来源:https://stackoverflow.com/questions/8985187/how-to-find-all-records-with-zero-number-of-has-many-assocations