Rails 4可以找到没有孩子的父母

Rails 4可以找到没有孩子的父母

我找到了一个答案,其中有一些可用的having例子可以找到有n孩子的父母,但同样不能用于找到没有孩子的父母(大概是因为连接不包括他们)。

scope :with_children, joins(:children).group("child_join_table.parent_id").having("count(child_join_table.parent_id) > 0")

谁能指出我正确的方向?


函数式编程
浏览 479回答 3
3回答

哔哔one

这应该做你想要的工作:Rails 3和4scope&nbsp;:without_children,&nbsp;includes(:children).where(:children&nbsp;=>&nbsp;{&nbsp;:id&nbsp;=>&nbsp;nil&nbsp;})这里的最大区别是joins成为a&nbsp;includes:一个include加载所有关系,如果它们存在,则join将仅加载关联的对象并忽略没有关系的对象。事实上,scope :with_children, joins(:children)应该足以让父母至少回到1个孩子。试试看!Rails 5请参阅下面的@ Anson的回答正如@MauroDias所指出的,如果它是你父母和孩子之间的自我指涉关系,那么上面的代码将不起作用。通过一些研究,我发现了如何做到这一点:考虑这个模型:class&nbsp;Item&nbsp;<&nbsp;ActiveRecord::Base &nbsp;&nbsp;has_many&nbsp;:children,&nbsp;:class_name&nbsp;=>&nbsp;'Item',&nbsp;:foreign_key&nbsp;=>&nbsp;'parent_id'如何返回没有孩子的所有项目(ren):Item.includes(:children).where(children_items:&nbsp;{&nbsp;id:&nbsp;nil&nbsp;})我怎么找那张children_items桌子的?Item.joins(:children)&nbsp;生成以下SQL:SELECT&nbsp;"items".*&nbsp;FROM&nbsp;"items"&nbsp; &nbsp;INNER&nbsp;JOIN&nbsp;"items"&nbsp;"children_items"&nbsp; &nbsp;ON&nbsp;"children_items"."parent_id"&nbsp;=&nbsp;"items"."id"所以我猜测Rails在自引用的情况下需要JOIN时使用表。

元芳怎么了

有一个坚实的Rails 4答案,但是对于那些来到Rails 5的人来说,你有更多的选择。使用Rails 5:从Rails 5开始,您还可以使用left_outer_joins来避免加载关联。它是在拉取请求#12071中引入的。scope&nbsp;:without_children,&nbsp;left_outer_joins(:children).where(children:&nbsp;{&nbsp;id:&nbsp;nil&nbsp;})对于有孩子的父母,MrYoshiji的Rails 4解决方案仍然可以使用:scope&nbsp;:with_children,&nbsp;joins(:children)

慕妹3146593

这就是我为Rails 5解决它的方法:scope&nbsp;:without_comments,&nbsp;->&nbsp;do &nbsp;&nbsp;left_outer_joins(:comments).where(comments:&nbsp;{&nbsp;id:&nbsp;nil&nbsp;})end
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby