mandar.gokhale
mandar.gokhale

Reputation: 1875

group records & get size of each group in rails

Hi I have table called Sold Products which stores buying information for product & schema is as follows.

id |username | product_id| timestamp

I have another table product its schema is

id | product_name | description 

I want to get most sold products. How to get that in active record?Please help.

Upvotes: 2

Views: 661

Answers (1)

iwasrobbed
iwasrobbed

Reputation: 46703

Two ways of doing this... the first one being easier and more efficient than the second:

Method 1: Use a counter cache

class SoldProduct < ActiveRecord::Base
  belongs_to :product, :counter_cache => true
end

Then you'd add a sold_products_count attribute to the Product table and find them using this:

Product.find(:all, :order => 'sold_products_count')

Method 2: Do it based on SQL

sales_count = Product.joins(:sold_products).count(:group=>"sold_products.product_id").sort_by{|product, sales| sales}.reverse
sales_count.each {|product, sales| puts "Product #{product} has #{sales} sales"}

Upvotes: 1

Related Questions