order products by association count belongs_to
Class Sale
belongs_to :product, :accessible => true
belongs_to :brand, :accessible => true
end
Class Product
has_many :sales
belongs_to :brand
end
Class Brands
has_many :products
开发者_Go百科has_many :sales
end
How do i get the brands that have the most product sales?
If you want to stay with activerecord you can use Calculations but it will take 2 queries to accomplish it:
>> brands = Sale.count(:id, :include => :brand, :group=> 'sales.brand_id', :limit => 5)
SQL (0.7ms) SELECT count(DISTINCT `sales`.id) AS count_id, sales.brand_id AS sales_brand_id FROM `sales` LEFT OUTER JOIN `brands` ON `brands`.id = `sales`.brand_id GROUP BY sales.brand_id LIMIT 5
=> #<OrderedHash {967032312=>3, 1392881137=>1}>
>> brands_with_most_sales = Brand.find(brands.keys)
Brand Load (0.5ms) SELECT * FROM `brands` WHERE (`brands`.`id` = 967032312)
=> [#<Brand id: 967032312, title: "brand-x", created_at: "2009-11-19 02:46:48", updated_at: "2009-11-19 02:46:48">]
Otherwise you might want to write you own query using find_by_SQL
精彩评论