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

これは私には恐ろしくスクリプトのように感じます。inject を使用してみましたが、思いどおりに動作させることができませんでした。誰かがこれを行うためのより良い方法を持っていますか?

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

クエリが 1 つだけ必要な場合は、group by を使用します。

于 2012-09-20T15:55:07.140 に答える