Refering to this: Is there any difference between GROUP BY and DISTINCT
Given a table that looks like this: name ------ barry dave bill dave dave barry john This query: SELECT name, count(*) AS count FROM table GROUP BY name; Will produce output like this: name count ------------- barry 2 dave 3 bill 1 john 1
What is the correct Rails convention here for ActiveModel to perform a GROUP BY with COUNT?
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...
Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet). Once you run that query by calling to_a , each , first etc. on that Relation a single instance or an array of ActiveRecord::Base instances will be returned.
Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Distinct
and Group By
are going to give you different results. To get the results you expect you'll want to use
Person.group(:name).count (1.2ms) SELECT COUNT(*) AS count_all, name AS name FROM "people" GROUP BY "people"."name" => {"Dan"=>3, "Dave"=>2, "Vic"=>1}
Seen above, group will return things as a hash. While distinct just returns the number of people in total, seen below.
Person.distinct(:name).count (0.4ms) SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people" => 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With