【问题标题】:Ruby - if all from relation attributes are equalRuby - 如果所有来自关系的属性都相等
【发布时间】:2014-10-02 22:40:26
【问题描述】:

我猜这个会很简单。

我有房间,也有客户。每个房间可以有很多客户。

在我的房间 #1 我有 4 个客户,他们都是女性 (client.sex = "F")。

我想检查这是对还是错。我这样做:

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

返回 true!这很酷。但是让我们认为性别可能是“F”、“M”、“A”、“B”、“C”、“N”,我想检查一个特定房间的所有客户是否具有相同的性别。我怎么能这样做?

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

当然可以:

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

但是有没有更好的方法来做到这一点?

【问题讨论】:

  • 好问题..我明天试试.. :-)

标签: ruby-on-rails ruby relation


【解决方案1】:

这有更少的数据库检索...

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

【讨论】:

    【解决方案2】:

    您甚至可以使用单个数据库查询来检查它:

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

    在这里你计算你的关系中不同的性别值,如果它大于 1,那么你在那里有一些不同的值。

    另外,如果您对呈现的值感兴趣,您可以提取不同值的数组,然后检查它的大小:

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

    【讨论】:

    • 感谢您展示如何使用“distinct”,非常有趣。
    • 但即使我在一个房间里有两个不同的“性别”,它也会返回 0。使用 pluck 时,我在控制台中得到了这个:NoMethodError: undefined method `pluck' for #<:nodes::distinct:0x0000000a1a45a0>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多