开发者

How do I search trough query results, to prevent making to many requests

I have the below set of queries, but I'm sure this isn't DRY. However, I can't find out how to filter trough the deals var instead of querying again for e开发者_运维知识库ach var. Is it possible?

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


Use GROUP BY SQL clause:

Hash[Deal.all(:select => 'status, count(*) as count', :group => 'status').map{|e| 
  [e.status, e.count]
}]

Edit: I forgot that you already have all the records loaded. In that case, you can get counts per status this way:

Hash[deals.group_by(&:status).map{|k,v| [k,v.count]}]


You can use following:-

Deal.find(:all, :select => 'status, count(id) as deal_count', :group => 'status')


You can use Array#select:

deals = Deal.all
won   = deals.select { |deal| deal.status == 'won' }.length
# similar for pending and lost 


I think you can use Ruby's inject function for this:

won = deals.inject(0) {|total, deal| deal.status == 'won' ? total + 1 : total }


if your Deal objects are ActiveRecord objects (which is typically the case for models), you can launch the count on the data base:

won = Deal.count_by_sql("select count(*) from deals where status = 'won'")

Another way to do it would be to write the sql query that would do the all the count for you, and group them by status:

count_by_status = Deal.find_by_sql("select status,count(*) from deals group by status;")

Then you can use the result (which will be an array of hashes I think).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜