0

I use the following query to return a list of records

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

which returns:

[#<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>]

How can I get a count for each rating label. For example, how many records out of the total are "Good" or how many are "Bad" etc.

4

2 回答 2

2

You can do that in at least 2 ways.

SQL

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

Array

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' }
于 2013-02-22T02:14:41.440 回答
0

You could try a group by:

Rating.where(:rating_set => 1, :product_id => 2186417).group(:label).count.each{ |k,v| puts "#{k} #{v}" }

Resource: http://guides.rubyonrails.org/active_record_querying.html#group

于 2013-02-22T05:58:16.310 回答