Created
June 25, 2009 20:27
-
-
Save JonCrawford/136140 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> Product.best_sellers | |
'SELECT `products`.*, COUNT(*) AS total FROM `products` INNER JOIN order_items ON order_items.product_id = products.id INNER JOIN orders ON orders.id=order_items.order_id WHERE ((orders.payment_state=3) GROUP BY products.id ORDER BY total DESC' | |
# Yay! | |
> @store.products.best_sellers | |
'SELECT `products`.*, COUNT(*) AS total FROM `products` INNER JOIN order_items ON order_items.product_id = products.id INNER JOIN orders ON orders.id=order_items.order_id WHERE (`products`.store_id = 464) AND (orders.payment_state=3) GROUP BY products.id ORDER BY products.name ASC' | |
# Nooo!!! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product < ActiveRecord::Base | |
belongs_to :store | |
default_scope :order => "products.name ASC" | |
named_scope :best_sellers, {:select => "`products`.*, COUNT(*) AS total", | |
:conditions => "orders.payment_state=#{Order::PaymentState::APPROVED}", | |
:group => "products.id", | |
:joins => "INNER JOIN order_items ON order_items.product_id = products.id INNER JOIN orders ON orders.id=order_items.order_id", | |
:order => "total DESC"} | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Store < ActiveRecord::Base | |
has_many :products, :dependent => :destroy | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment