Rails 4 范围可以找到没有孩子的父母 [英] Rails 4 scope to find parents with no children
问题描述
我找到了一个 answer,其中有一些可用的 have
示例,用于使用 n
个孩子,但同样不能用于查找没有孩子的父母(大概是因为连接排除了他们).
I found one answer that had some usable having
examples for finding parents with n
children, but the same is not usable for finding parents with no children (presumably since the join excludes them).
scope :with_children, joins(:children).group("child_join_table.parent_id").having("count(child_join_table.parent_id) > 0")
谁能指出我正确的方向?
Can anyone point me in the right direction?
推荐答案
Rails 3 &4
scope :without_children, includes(:children).where(:children => { :id => nil })
这里最大的区别是 joins
变成了 includes
:一个包含加载所有的关系,如果它们存在,连接将只加载关联的对象并忽略没有关系的对象.
The big difference here is the joins
becoming a includes
: an include loads all the relations, if they exists, the join will load only the associated objects and ignore the object without a relation.
事实上,scope :with_children, joins(:children)
应该足以返回至少有 1 个孩子的 Parent.试试看!
In fact, scope :with_children, joins(:children)
should be just enough to return the Parent with at least 1 child. Try it out!
见下面@Anson 的回答
See @Anson's answer below
<小时>
Gem activerecord_where_assoc
activerecord_where_assoc
gem 可以为 Rails 4.1 到 6.0 做到这一点.
Gem activerecord_where_assoc
The activerecord_where_assoc
gem can do this for Rails 4.1 up to 6.0.
scope :without_children, where_assoc_not_exists(:children)
无缝处理自引用关系.
这也避免了诸如 joins
使查询为单个记录返回多行之类的问题.
This also avoids issues such as joins
making the query return multiple rows for a single record.
正如@MauroDias 指出的那样,如果是你的父母和孩子之间的自我参照关系,上面的代码将不起作用.
As @MauroDias pointed out, if it is a self-referential relationship between your parent and children, this code above won't work.
通过一些研究,我找到了方法:
With a little bit of research, I found out how to do it:
考虑这个模型:
class Item < ActiveRecord::Base
has_many :children, :class_name => 'Item', :foreign_key => 'parent_id'
如何退回所有没有孩子的物品:
How to return all items with no child(ren):
Item.includes(:children).where(children_items: { id: nil })
我是如何找到children_items
表的?
Item.joins(:children)
生成以下 SQL:
SELECT "items".*
FROM "items"
INNER JOIN "items" "children_items"
ON "children_items"."parent_id" = "items"."id"
所以我猜测 Rails 在自引用情况下需要 JOIN 时使用表.
So I guessed that Rails uses a table when in need of a JOIN in a self-referential case.
类似问题:
这篇关于Rails 4 范围可以找到没有孩子的父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!