I have a Meeting model which has multiple Participants. Participant has a few boolean attributes: accepted, rejected ect. I would like check all participants of a meeting if their are all accepted == true. Is there a quick way to check all boolean attributes of child objects similar to sum method (as in total_price = items.sum(&:price) )?
Asked
Active
Viewed 1,687 times
2 Answers
4
meeting.participants.all?(&:acctepted)
Take a look at the enumerable module

topek
- 18,609
- 3
- 35
- 43
-
1just be aware that this solution loads all participants into memory and then loops through them, as opposed to the (better) solution from mu below, which should be log(n) – klochner Oct 24 '11 at 07:47
-
depends on the situation. if the participants are already loaded my solution does not bother the DB with an extra query, if not mu's solution is better. – topek Oct 24 '11 at 09:11
-
Thanks klockner. I didn't realized. – AdamNYC Oct 24 '11 at 16:09
-
@topek - no argument there, I assumed he was just working with the Meeting model, but you are correct about not hitting the db if participants are loaded – klochner Oct 24 '11 at 18:44
3
You could use count
:
all_true = items.count(:conditions => [ 'bool_column = ?', true ]) == items.count
And if you don't have NULLs to worry about in your boolean column:
all_true = items.count(:conditions => [ 'bool_column = ?', false ]) == 0
Or you could do it this way (as suggested by klochner) to get around the usual NULL problems and avoid a double count
:
all_true = items.count(:conditions => [ 'bool_column = ? or bool_column is null', false ]) == 0
You could check several boolean columns at once too.

Community
- 1
- 1

mu is too short
- 426,620
- 70
- 833
- 800
-
1the second version would work with null if you just add "bool_column is null or bool_column = ?",false – klochner Oct 23 '11 at 21:05
-
@klochner: Right, thanks for pointing that out, I've patched the answer accordingly. – mu is too short Oct 23 '11 at 21:09