我有以下一组查询,但我确定这不是DRY。但是,我无法找到如何通过deal var过滤而不是为每个var再次查询。有可能吗?
deals = Deal.all
won = Deal.find( :all, :conditions => ["status = 'won'"] ).count
pending = Deal.find( :all, :conditions => ["status = 'pending'"] ).count
lost = Deal.find( :all, :conditions => ["status = 'lost'"] ).count
答案 0 :(得分:5)
使用GROUP BY SQL子句:
Hash[Deal.all(:select => 'status, count(*) as count', :group => 'status').map{|e|
[e.status, e.count]
}]
编辑:我忘了你已经加载了所有记录。在这种情况下,您可以通过这种方式获得每个状态的计数:
Hash[deals.group_by(&:status).map{|k,v| [k,v.count]}]
答案 1 :(得分:1)
您可以使用以下内容: -
Deal.find(:all,:select =>'status,count(id)as deal_count',:group =>'status')
答案 2 :(得分:1)
您可以使用Array#select:
deals = Deal.all
won = deals.select { |deal| deal.status == 'won' }.length
# similar for pending and lost
答案 3 :(得分:0)
我认为你可以使用Ruby的注入函数:
won = deals.inject(0) {|total, deal| deal.status == 'won' ? total + 1 : total }
答案 4 :(得分:0)
如果您的Deal对象是ActiveRecord对象(通常是模型的情况),您可以在数据库上启动计数:
won = Deal.count_by_sql("select count(*) from deals where status = 'won'")
另一种方法是编写sql查询,为您完成所有计数,并按状态对它们进行分组:
count_by_status = Deal.find_by_sql("select status,count(*) from deals group by status;")
然后你可以使用结果(我认为这将是一个哈希数组)。