How to find all records with zero number of has_many assocations?

旧巷老猫 提交于 2020-01-05 07:51:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!