ruby on rails - count number of records with matching values associated with a specific record -


i have model x has_many models y. y has field called 'type', can a, b, or c. know on show view x, can use:

<%= @x.ys.count %> 

to return number of y objects associated instance of x. or, can use:

<%= y.group(:type).count["a"] %> 

to return total number of y objects of type a, across x objects.

what if want return number of y objects of type associated particular instance of x, such @x particular instance show view being accessed?

edit:

the ys method defined within x.rb 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 fact 'through' relationship interfering ability access methods 'where'?

it should simple as:

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

if ys method returns array instead association, can tweak this:

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

optimizing code

you can change code make 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 place filtering function in queries instead of selecting array.

then:

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

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -