这是我现在正在做的:
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 但无法让它按照我想要的方式工作。有没有人有更好的方法来做到这一点?
最佳答案
改进@xdazz 的回答
def get_counts
Product.where(some_attribute: ['a','b','c']).
count(group: "some_attribute")
end
这将返回以下形式的散列:
{'a' => 3, 'b' => 4, 'c' => 5}
关于ruby-on-rails - 更多 ruby 方法来计算符合条件的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516327/