Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择所有子对象都没有子对象的对象_Sql_Ruby On Rails 3_Squeel - Fatal编程技术网

Sql 选择所有子对象都没有子对象的对象

Sql 选择所有子对象都没有子对象的对象,sql,ruby-on-rails-3,squeel,Sql,Ruby On Rails 3,Squeel,我有以下三级模型层次结构: class Parent < AR::Base has_many :children end class Child < AR::Base has_many :grandchildren belongs_to :parent attr_accessible :my_number end class Grandchild < AR::Base belongs_to :child end 类父类

我有以下三级模型层次结构:

class Parent < AR::Base
  has_many :children
end

class Child < AR::Base
  has_many :grandchildren
  belongs_to :parent

  attr_accessible :my_number
end

class Grandchild < AR::Base
  belongs_to :child
end
类父类
预计所有的
父项
都将有多个子项
,但每个
子项
可能有或可能没有任何
子项

我想检索所有
子对象
没有
孙子对象的
父对象
对象。我该怎么做?我更喜欢滑轨,而且我有橡皮泥;但我会接受原始SQL


如果你能给我所有
Parent
对象,所有
子对象都没有
孙子对象,所有
子对象都有
my_number<5

的话,我想经过一点研究,我通过使用
having
子句得到了解决方案

您可以将此范围添加到您的
父级
模型中。注意,我们需要手动定义
连接
,以便使用
左连接
,而不是默认的
内部连接
。更多信息

对于第二个问题,假设
:my_number
是存储在DB中的属性,则可以执行以下操作:

Parent.with_children_having_no_grand_children.where(children: { my_number: 5 }))

我注意到,当然,
Parent.all.select{| p | p.children.all?{| c | c.genderrens.empty?&&c.my|u number<5}
起作用。不过,这并不完全有效。
Parent.with_children_having_no_grand_children
Parent.with_children_having_no_grand_children.where(children: { my_number: 5 }))