I am working on an application where User has many projects and Project many roles. Role has a boolean filled attribute indicating when someone took this role.
I would like to build a query that returns all projects that either have no roles or have roles that have been filled . This is the closest I have so far:
@user.projects.includes(:roles).where("roles.id IS NULL OR roles.filled IS TRUE").references(:roles)
The problem is that part of roles.filled IS TRUE request corresponds to projects with a mixture of filled and unfilled roles. I need this to fit projects that fill all the roles.
Finding PostgreSQL documentation looks like bool_and is probably the way to go, but my SQL skills are small and I'm glad I wasn’t able to get it working yet.
I understand that I could do this easily with select or reject , but I would like to keep it efficient by simply querying the database.
Can someone offer some advice please?
Update: models (simplified) and their relationships:
application / models / user.rb
class User < ActiveRecord::Base has_many :projects end
application / models / project.rb
class Project < ActiveRecord::Base belongs_to :user has_many :roles end
application / models / role.rb
class Role < ActiveRecord::Base belongs_to :project
Simon source share