0

我用下面的查询返回的记录的Rails得到阵列

Rating.find(:all, :conditions => ["rating_set = ? and product_id = ?", 1, 2186417]) 

它返回一个列表记录数:

[#<Rating id: 5, label: "Good", rating: 3.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2186417, notes: "exact match", rating_set: 1, product_id: 2186417>, #<Rating id: 6, label: "Good", rating: 3.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2054442, notes: "", rating_set: 1, product_id: 2186417>, #<Rating id: 7, label: "Fair", rating: 2.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2403501, notes: "", rating_set: 1, product_id: 2186417>, #<Rating id: 8, label: "Bad", rating: 3.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2344645, notes: "", rating_set: 1, product_id: 2186417>]

我怎样才能得到每个等级标签计数。例如,有多少记录了总的是“好”或有多少是“坏”等

回答

2

你可以做,在至少2种方式。

SQL

klass = Rating.where(rating_set: 1, product_id: 2186417]) 
good_count = klass.where(label: 'Good').count 
bad_count = klass.where(label: 'Bad').count 

阵列

ratings = Rating.where(rating_set: 1, product_id: 2186417]).all 
good_count = ratings.count { |r| r.label == 'Good' } 
bad_count = ratings.count { |r| r.label == 'Bad' }