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/5463774 to your computer and use it in GitHub Desktop.
Save JamesDullaghan/5463774 to your computer and use it in GitHub Desktop.
ActiveRecord Schneems Grouping Tutorial Notes

#Grouping#

prods = Product.group(:price).count

Returns

puts prods
=> {573=>3, 574=>4, 575=>6, 576=>4}

The group method returns a hash of all prices, along with the count of each price. For example, there must be 3 items priced at 573

####Grouping is a way for us to get distinct values####

prods = Product.where(:name => "Widget")
prods.count
=> 5

prods = Product.where(:name => "Widget").group(:name)
puts prod
=> [#<Product id: 1,
              user_id: 1,
              name: "HD Electric Amplifier",
              price: 269,
              created_at: "2012-07-07 21:08:22",
              updated_at: "2012-07-09 01:33:57">]

Can also use DISTINCT()

prods = Product.where(:name => "Widget")
prods.count('DISTINCT(name)')
=> 1

Pure Ruby

prods.count(:name, :distinct => true)
=> 1

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