1

这是我现在正在做的事情:

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

这对我来说感觉非常糟糕。我尝试使用注入,但无法让它按我想要的方式工作。有没有人有更好的方法来做到这一点?

4

2 回答 2

2

改进@xdazz 的答案

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

这将返回以下形式的哈希:

{'a' => 3, 'b' => 4, 'c' => 5}
于 2012-09-20T15:58:19.717 回答
1
def get_counts
  return Product.where(:some_attribute => 'a').count, Product.where(:some_attribute => 'b').count, Product.where(:some_attribute => 'c').count
end

如果您只需要一个查询,请使用 group by。

于 2012-09-20T15:55:07.140 回答