Guido
Guido

Reputation: 387

Ruby - if all from relation attributes are equal

this one I guess is going to be simple.

I have Rooms and I have Clients. Each room can have many clients.

In my room #1 I have 4 clients, and they are all female (client.sex = "F").

I want to check if this is true or false. And I do this:

Room.first.clients.all? {|c| c.sex == "F" }

And that returns true! Which is cool. But lets think that sex could be "F", "M", "A", "B", "C" "N" and I want to check if all the clients of one specific room have the same sex. How could I do that?

Room.first.clients.all? {|c| c.sex == "same as all other clients from this room" }

Of course I could do:

sexbase = Room.first.clients.first.sex
Room.first.clients.all? {|c| c.sex == sexbase }

But it there any better way to do this?

Upvotes: 1

Views: 84

Answers (2)

alno
alno

Reputation: 3616

You can even check it with single database query:

Room.first.clients.distinct.count(:sex) > 1

Here you count distinct sex values in your relation, and if it's more than 1 than you have some different values there.

Also, if you are interested in values presented, you may extract array of distinct values and then check it' size:

values = Room.first.clients.distinct.pluck(:sex) # ['M', 'F'] or ['M'], for example
values.size > 1

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36860

This has less database retrievals...

array = Room.first.clients.pluck(:sex)
array.count(array[0]) == array.count

Upvotes: 1

Related Questions