Skip to content

Instantly share code, notes, and snippets.

@hendricius
Created May 9, 2014 16:37
Show Gist options
  • Save hendricius/b912db612770cdcd26c7 to your computer and use it in GitHub Desktop.
Save hendricius/b912db612770cdcd26c7 to your computer and use it in GitHub Desktop.
Join creating many results
# Doing the count by hand vs count from the join https://www.dropbox.com/s/sms6mot4ly6b54o/Screenshot%202014-05-09%2018.33.09.png
@shopping_setups = ShoppingSetup.joins(:company).
joins("LEFT JOIN products on companies.id = products.company_id").
joins("LEFT JOIN categories on companies.id = categories.company_id").
select("shopping_setups.*").
select("COUNT(products.company_id) AS products_count").
select("COUNT(categories.company_id) AS categories_count").
group("shopping_setups.id, companies.id, products.company_id, categories.company_id")
class ShoppingSetup
belongs_to :company
end
class Company
has_one :shopping_setup
has_many :products
has_many :categories
end
class Product
belongs_to :company
end
class Category
belongs_to :company
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment