我如何编写一个计算字段实例的Rails finder方法?

问题描述 投票:0回答:1

我正在使用Rails5。我有一个模型,

class User < ApplicationRecord
    ...
    has_many :emails

我如何编写查找程序方法来查找所有拥有多个电子邮件的用户?我似乎无法弄清楚如何在where子句中使用“计数”。

ruby-on-rails count ruby-on-rails-5 finder
1个回答
0
投票

这将加入电子邮件表,并返回计数超过一个的用户。

scope :with_more_than_one_email, -> {
  joins(:emails).having('COUNT(emails) > 1').group(:id)
}

您可以用User.with_more_than_one_email调用它

© www.soinside.com 2019 - 2024. All rights reserved.