NeyLive
NeyLive

Reputation: 417

How can I query to see if all records in a child model have the same value for an attribute?

First off, I know this is really basic stuff for most of you but I'm still learning and I would appreciate any help.

I have a boolean column in my child table. I am trying to query all the child records associated with a parent to see whether the value of the boolean column is true for all those child records or not.

What I have now is this:

  if Parent.children.count(:conditions => [ 'boolean_column = ?', true ]) == Parent.children.count
    return true

My logic with that being that if the count of all the associated child records is equal to the count of the associated child records where the boolean column is true, then that should return true, but of course it doesn't work.

What is the rails way of doing this, if there is one?

Upvotes: 2

Views: 1553

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

You can achieve this by doing only 1 query. But to do, you need to make sure first that the boolean column should never have NULL, except true or false. So adding NOT NULL constraint will make sure that column will never have NULL. After that you can run the below query:

hash = Children.
  group(:boolean_column).
  where(parent_id: 12).
  count(:boolean_column)

12 should be replaced by your actual id of the parent. Now, do check if hash has the false as a key, like hash.has_key?(false). If there is no false key, you can assert that all children has true to the boolean column.

Upvotes: 1

Fakhir Shad
Fakhir Shad

Reputation: 1101

You can do it as

Parent.children.where("boolean_column = ?", true).count == Parent.children.count

Upvotes: 0

Related Questions