首页 > 解决方案 > 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从上述两个失败的查询中获取?

标签: ruby-on-railspostgresqlactiverecord

解决方案


推荐阅读