Josh
Josh

Reputation: 5721

More ruby way to count objects that match criteria

Here is what I am doing now:

def get_counts
  products = Product.all
  a_count, b_count, c_count = 0, 0, 0
  products.collect{ |p| a_count+=1 if p.some_attribute == 'a' }
  products.collect{ |p| b_count+=1 if p.some_attribute == 'b' }
  products.collect{ |p| c_count+=1 if p.some_attribute == 'c' }
  return a_count, b_count, c_count
end

This feels horribly scripty to me. I tried using inject but couldn't get it to work how I wanted. Does anyone have a better way to do this?

Upvotes: 1

Views: 100

Answers (2)

PinnyM
PinnyM

Reputation: 35533

To improve on @xdazz's answer

def get_counts
  Product.where(some_attribute: ['a','b','c']).
          count(group: "some_attribute")
end

This will return a hash in the form:

{'a' => 3, 'b' => 4, 'c' => 5}

Upvotes: 2

xdazz
xdazz

Reputation: 160843

def get_counts
  return Product.where(:some_attribute => 'a').count, Product.where(:some_attribute => 'b').count, Product.where(:some_attribute => 'c').count
end

If you want only one query, then use group by.

Upvotes: 1

Related Questions