Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesDullaghan/5521790 to your computer and use it in GitHub Desktop.
Save JamesDullaghan/5521790 to your computer and use it in GitHub Desktop.
ActiveRecord Schneems Tutorial HAVING notes

#Having#

Objective : Find all of the products that have more than 5 duplicate prices

Group & Having

prods = Product.group(:price).having("count(price) > 5")
puts prods
=> [#<Product id: 1743,
              user_id: 1363,
              name: "Performance Electric Component",
              price: 29,
              created_at: "date",
              updated_at: "date">,
    #<Product id: 1383,
              user_id: 1005,
              name: "Gel Side Compressor",
              price: 156,
              created_at: "date",
              updated_at: "date">]
puts prods.all.count
=> 24
puts Product.count
=> 2124

This is taking the products and grouping them by price.

  • It then looks through the products grouped by price
  • Counts the total number of products which have more than 5 other products which have the same price.

Ex.

  • Soda: $5
  • Toothpaste: $5
  • Shoelaces: $5
  • Coffee cup: $5
  • Boots: $5
  • Bandaids: $5

There are 6 items/products with the same price, therefore greater than 5. This would count as 1. Each of these products would be returned if we did

prods = Product.group(:price).having("count(price) > 5")
puts prods

Use having as a grouped where clause

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment