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' }