计算具有与特定记录关联的匹配值的记录数

count number of records with matching values associated with a specific record

我有一个模型 X,其中 has_many 个模型是 Y。Y 有一个名为 'type' 的字段,可以是 A、B 或 C。我知道在 X 的显示视图中,我可以使用:

<%= @x.ys.count %>

到return与X实例关联的Y对象的数量。或者,我可以使用:

<%= Y.group(:type).count["A"] %>

至 return 所有 X 对象中类型 A 的 Y 对象总数。

如果我只想 return 与 X 的特定实例关联的类型 A 的 Y 对象的数量怎么办,这样 @x 就是正在访问其显示视图的特定实例?

编辑:

ys 方法在 x.rb 中定义如下:

Class X < ActiveRecord::Base
  has_many :fs
  has_many :gs
  has_many :f_ys, through: :fs, source: :ys
  has_many :g_ys, through: :gs, source: :ys

  def ys
    f_ys + g_ys
  end
end

这是一个 'through' 关系这一事实是否会干扰我访问某些方法(如 'where')的能力?

它应该很简单:

<%= @x.ys.where(type: 'A').size %>

如果 ys 方法 returns 一个数组而不是一个关联,你可以像这样调整它:

<%= @x.ys.select{|y| y.type == 'A'}.size %>

优化代码

您可以将代码更改为这样以使其更快:

def ys(type = nil)
  if type
    f_ys.where(type: type) + g_ys.where(type: type)
  else
    f_ys + g_ys
  end
end

为了将过滤函数放在查询中而不是select数组。

然后:

<%= @x.ys.count %>
<%= @x.ys('A').count %>