Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #9440 (new enhancement)

Opened 9 months ago

Last modified 8 months ago

[PATCH] allow :distinct_records option for calculations

Reported by: jcoglan Assigned to: core
Priority: normal Milestone: 2.x
Component: ActiveRecord Version: edge
Severity: normal Keywords: unverified calculation sum distinct
Cc: sur

Description

Let's say you want to find the sum of the prices of a bunch of products in your database, and the criteria used for selecting products involve using :include to bring in associated tables. Those LEFT OUTER JOIN statements may result in the base record (Product) being duplicated for every association found. e.g. if product number 1 has three comments associated with it, then Product.sum(:price, :include => :comments, :conditions => ...) will include product number 1 in three rows of the SQL result set. I only want its price added to the sum once, but I can't use the :distinct option because the prices I'm adding up aren't necessarily unique.

This patch adds a :distinct_records option to ActiveRecord::Calculations::ClassMethods#calculate, which replaces the table name in the SQL query with another SQL SELECT query to find a distinct set of records to be summed. I've included a couple tests to illustrate the effect, and I've run this under MySQL. I'm not sure whether all other DBs support this syntax so the patch may need work.

Attachments

calculations_with_distinct_records_with_tests.diff (4.5 kB) - added by jcoglan on 01/30/08 23:25:11.
parallel_calculations_and_distinct_records_with_tests.diff (10.2 kB) - added by jcoglan on 01/30/08 23:25:29.

Change History

08/30/07 13:25:09 changed by sur

  • cc set to sur.

09/06/07 08:35:50 changed by jcoglan

This ticket conflicts with the patch for #9487, so I'm adding a patch for both these tickets. See parallel_calculations_and_distinct_records_with_tests.diff.

09/16/07 10:40:32 changed by jcoglan

  • keywords changed from calculation sum distinct to unverified calculation sum distinct.

01/30/08 23:25:11 changed by jcoglan

  • attachment calculations_with_distinct_records_with_tests.diff added.

01/30/08 23:25:29 changed by jcoglan

  • attachment parallel_calculations_and_distinct_records_with_tests.diff added.