ruby-on-rails - 我如何构造此 Rails/PostgreSQL 查询以根据模型子项的属性返回模型实例?

标签 ruby-on-rails postgresql

我正在开发一个应用程序,其中 User 有很多项目,Project 有很多角色。 Role 有一个 bool 值 filled 属性来指示某人何时担任该角色。

我想构建一个查询,返回所有没有角色角色已全部填充 的项目。这是我迄今为止最接近的:

@user.projects.includes(:roles).where("roles.id IS NULL OR roles.filled IS TRUE").references(:roles)

问题是查询的 roles.filled IS TRUE 部分正在匹配具有填充和未填充角色混合的项目。我只需要它来匹配所有角色都已填充的项目。

搜索 PostgreSQL 文档,它看起来像 bool_and可能是要走的路,但我的 SQL 技能不是很好,我还没有设法让它工作。

我意识到我可以使用 selectreject 轻松地做到这一点,但我想通过查询数据库来保持高效。

有人可以提供一些建议吗?

更新:(简化的)模型及其关系:

app/models/user.rb

class User < ActiveRecord::Base
  has_many :projects
end

app/models/project.rb

class Project < ActiveRecord::Base
  belongs_to :user
  has_many :roles
end

app/models/role.rb

class Role < ActiveRecord::Base
  belongs_to :project

  # `filled` is a boolean attribute with a default value of false
end

最佳答案

你必须求助于 aggregate function因为条件适用于许多记录的组合(roles.filled 的所有字段都必须为真)。因此,您按 projects.id 对所有角色进行分组,并检查 every(roles.filled) 是否为真:

这是一个建议:

@user.projects.
      joins("left outer join roles on roles.project_id = projects.id").
      group("projects.id").
      having("every(roles.filled IS TRUE) OR every(roles.id IS NULL)")
      select("projects.*")

更新:好的,这是此 SQL 背后的逻辑:

for every project, I'll check if it has NO roles.id OR ONLY roles.filled. The reason you cannot use the where clause for roles.id IS TRUEis that it would only select those, before grouping and filtering in the having clause and therefore excluding the roles.filledrows. In other words it would be the equivalent of doing roles.id is NULL AND Roles.filled IS TRUE

关于ruby-on-rails - 我如何构造此 Rails/PostgreSQL 查询以根据模型子项的属性返回模型实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34719966/

相关文章:

ruby-on-rails - 给定 id 列表,如何更新所有模型的 bool 属性?

mysql - Ruby on Rails 和查询(理解问题)

ruby-on-rails - 向 Rails 观察者传递额外的参数

sql - 在 linux 中插入数据时在 postgres 列中保留新行

sql - 使用筛选行比较排除约束

sql - PG 功能故障排除

linux - 如何为基于 Linux 的数据库服务器设置 Azure 自托管集成运行时

javascript - 在 Rails 中提供静态 JSON 对象文件

python - 如何在 MacOs X 10.5 上安装 plpython?

ruby-on-rails - I18N 键,用于在模块中分组的 rails 模型