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

时间:2015-10-30 22:13:59

标签: ruby-on-rails ruby-on-rails-4 has-many

I have a model X which has_many models Y. Y has a field called 'type', which can be A, B, or C. I know that on the show view for X, I can use:

<%= @x.ys.count %>

to return the number of Y objects associated with an instance of X. Or, I can use:

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

To return the TOTAL number of Y objects of type A, across all X objects.

What if I want to only return the number of Y objects of type A associated with a particular instance of X, such that @x is the particular instance whose show view is being accessed?

EDIT:

The ys method is defined within x.rb as such:

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

Could the fact that this is a 'through' relationship be interfering with my ability to access some methods like 'where'?

1 个答案:

答案 0 :(得分:1)

It should be as simple as:

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

If the ys method returns an array instead than an association, you can tweak it like this:

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

Optimizing code

You can change your code to this to make it faster:

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

in order to place the filtering function in the queries instead of selecting the array.

Then:

<%= @x.ys.count %>
<%= @x.ys('A').count %>
相关问题