I have a task to determine if all boolean attributes of a subset of records are true
. After using sum
, I expected to have a similar method to work with booleans. However, I could not find such a thing.
I feel that there is a big chance that the answer is very clear, straightforward and available via a simple Google search, but I am not able to think of the correct phrases to search for it.
Example of what I am trying to achieve:
[
#<User id: 1, name: "John", arborist: true>,
#<User id: 2, name: "Ben", arborist: true>,
#<User id: 3, name: "Betty", arborist: false>,
]
Should return false
[
#<User id: 1, name: "John", arborist: true>,
#<User id: 2, name: "Ben", arborist: true>,
#<User id: 3, name: "Betty", arborist: true>,
]
Should return true
At the moment I am using count
.
all_arborists? = ( User.count == User.where(arborist: true).count )
It gets me the result, but I feel there is more to it than my mind can figure out.
CodePudding user response:
You can simply check if there is a single non-arborist in the database:
all_arborists = !User.exists?(arborist: false)
You can defined it as a class method, rails magic will make it available on all scopes:
class User
def self.all_arborists?
!exists?(arborist: false)
end
end
User.where(some_condition: foo).all_arborists?
CodePudding user response:
If you already have the records loaded in memory, and you're working with an Array, you can use Ruby's #all?
method:
all_arborists = records.all? { |r| r.arborist }
If the records are in the DB and you don't want to load them in memory, then you need a SQL query, and what you tried is on the right path:
non_arborists = User.where(some_condition: foo).where(arborist: false).count
all_arborists = non_arborists == 0