ruby-on-rails - rails get total count in 有很多关系
问题描述
我正在尝试使用自定义选择计数进行一些分组。这是我的模型
class RescueGroup < ApplicationRecord
has_many :addresses, dependent: :delete_all
has_many :emails, -> { where(type: Contact.types[:email]) }, class_name: 'Contact'
has_many :phones, -> { where(type: Contact.types[:phone]) }, class_name: 'Contact'
end
class Contact < ApplicationRecord
self.inheritance_column = nil
enum type: [:email, :phone, :facebook]
belongs_to :rescue_group
end
class Address < ApplicationRecord
belongs_to :rescue_group
end
我正在尝试构建一个范围,使我能够获取每个救援组的所有电子邮件的计数,以便我可以在视图中显示计数。
但如果我这样做,它会起作用,我可以得到这个email_count
领域。
RescueGroup.select('rescue_groups.*, count(contacts.id) FILTER(where type = 0) as email_count')
.joins(:emails)
.includes(:addresses)
.group(:id)
.first
.email_count
但是一旦我添加了这样的过滤器:
RescueGroup.select('rescue_groups.*, count(contacts.id) FILTER(where type = 0) as email_count')
.joins(:emails)
.includes(:addresses)
.group('rescue_groups.id, addresses.id')
.where.not(addresses: { state: 'tas' })
.first
.email_count
它将失败并出现以下错误
NoMethodError: undefined method `email_count'
如果我使用第一个查询并尝试采摘它也会失败email_count
:
RescueGroup.select('rescue_groups.*, count(contacts.id) FILTER(where type = 0) as email_count')
.joins(:emails)
.includes(:addresses)
.group(:id)
.pluck(:email_count)
所以我的问题是如何email_count
从上述两个失败的查询中获取?
解决方案
推荐阅读
- excel - 将“&”符号插入 Office 功能区 XML 控件的 Label 属性
- javascript - Node.js:如何处理在字典中查找同名的不同城市?
- spring-boot - 如何在 springboot 项目反应器 Mono 流(用 Kotlin 编写)中进行条件检查?
- c# - 当版本更改时,如何确保共享程序集在 .NET 中与 ABI/API 兼容?
- python - Dict - 如果每个键有多个值,则提取最后一个元素
- visual-studio - 在 Visual Studio 2019 中消失的文本
- jquery - 我想从重定向 URL 中删除尾部斜杠
- python - 用于从指定日期范围获取记录的域返回该范围之外的记录
- c - 数组元素在函数外“丢失”
- azure - Web 应用程序防火墙是否可以在给定的 url 模式上返回 404?