检查 Rails 中所有子对象的布尔属性

发布于 2024-12-11 15:14:37 字数 143 浏览 0 评论 0原文

我有一个有多个参与者的会议模型。参与者有一些布尔属性:接受、拒绝等。我想检查会议的所有参与者是否都被接受== true。 是否有一种类似于 sum 方法的快速方法来检查子对象的所有布尔属性(如total_price = items.sum(&:price) )?

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) )?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦毁影碎の 2024-12-18 15:14:38

您可以使用 count

all_true = items.count(:conditions => [ 'bool_column = ?', true ]) == items.count

如果你的布尔列中没有 NULL 需要担心:

all_true = items.count(:conditions => [ 'bool_column = ?', false ]) == 0

或者你可以这样做(如 klochner)来解决常见的 NULL 问题并避免双重计数

all_true = items.count(:conditions => [ 'bool_column = ? or bool_column is null', false ]) == 0

您可以检查几个布尔列也立刻。

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.

凑诗 2024-12-18 15:14:37
meeting.participants.all?(&:acctepted)

看一下可枚举模块

meeting.participants.all?(&:acctepted)

Take a look at the enumerable module

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文