我使用以下查询返回记录列表
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>]
如何计算每个评级标签。例如,总数中有多少记录是“好”或有多少是“坏”等。
答案 0 :(得分: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' }
答案 1 :(得分:0)
您可以通过以下方式尝试分组:
Rating.where(:rating_set => 1, :product_id => 2186417).group(:label).count.each{ |k,v| puts "#{k} #{v}" }
资源:http://guides.rubyonrails.org/active_record_querying.html#group