轨道4的范围找父母,没有孩子 [英] Rails 4 scope to find parents with no children

查看:261
本文介绍了轨道4的范围找父母,没有孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一个答案说了一些有用的例子寻找父母 N 的孩子,但同样不是找父母没有子女可用(presumably自加盟排除它们)。

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?

推荐答案

这应该做你想要的工作:

This should do the job you want:

scope :without_children, includes(:children).where(:children => { :id => nil })

这里最大的区别是加入成为包括:一个包括加载所有关系,如果他们存在,连接只会加载关联对象,而忽略对象没有关系。

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.

其实,范围:with_children,加入(:儿童)应该是刚够至少有1名儿童返回父。试试吧!

In fact, scope :with_children, joins(:children) should be just enough to return the Parent with at least 1 child. Try it out!

由于@MauroDias指出,如果这是你的父母和孩子,这code以上将无法正常工作的一种自我指涉的关系

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(:儿童)生成的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.

类似的问题:

  • <一个href="http://stackoverflow.com/questions/23633301/how-to-query-a-model-based-on-attribute-of-another-model-which-belongs-to-the-fi/23633352#23633352">How查询一个模式的基础上,属于所述第一模型的另一模型的属性?中
  • <一个href="http://stackoverflow.com/questions/18234602/rails-active-record-querying-association-with-exists/18234998#18234998">Rails与活动记录查询协会'存在'
  • <一个href="http://stackoverflow.com/questions/13515225/rails-3-has-one-has-many-with-lambda-condition/13516285#13516285">Rails 3,HAS_ONE /的has_many与拉姆达条件
  • <一个href="http://stackoverflow.com/questions/24266069/join-multiple-tables-with-active-records/24266583#24266583">Join与活跃记录多个表
  • How to query a model based on attribute of another model which belongs to the first model?
  • Rails active record querying association with 'exists'
  • Rails 3, has_one / has_many with lambda condition
  • Join multiple tables with active records

这篇关于轨道4的范围找父母,没有孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆