ruby-on-rails - rails : find all parents with all children having a particular attribute

标签 ruby-on-rails ruby activerecord

我需要找到所有子级状态为 1 的父级。

如果其中一个 child 不是status = 1;那么没有选择父级。

class Parent
  has_many :children
end

class Child
  status = [ 0, 1 ]
end

我已经试过了,但是没用。

Parent.left_outer_joins(:children).where("children.status = ?", 1)

它不起作用,因为我仍然得到 Parent with children status=0

最佳答案

我想你需要一个子查询:

Parent.where.not(id: Children.where.not(status: 1).select(:parent_id))

关于ruby-on-rails - rails : find all parents with all children having a particular attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55639108/

相关文章:

ruby - 为什么这个 Ruby 程序不将堆内存返回给操作系统?

ruby-on-rails - 在 ActiveRecord 查询中包含相关数据的计算

mysql - mysql 中的 ActiveRecord DATETIME 列值

ruby-on-rails - 如何避免 Rails 应用程序中的竞争条件?

ruby-on-rails - 如何从已连接相同模型/类/表的表中进行选择?

ruby-on-rails - 新部署后 Unicorn 未正确断开数据库连接

ruby-on-rails - 了解 Rails 真实性 token

java - jQuery/Ajax 显示“另存为”对话框,用于下载从 servlet 发送的文件

mysql - pgloader - 无法以用户 "localhost": Condition QMYND:MYSQL-UNSUPPORTED-AUTHENTICATION was signalled 的身份在 "root"(端口 3306)连接到 mysql

ruby-on-rails - 使用多个条件创建 ActiveRecord 范围