Skip to content
This repository
Browse code

Delegate count to Relation

  • Loading branch information...
commit 73b179eb689611ac0518584b21f2304756a7e981 1 parent 88ffba2
Pratik lifo authored
63 activerecord/lib/active_record/calculations.rb
@@ -3,68 +3,7 @@ module Calculations #:nodoc:
3 3 extend ActiveSupport::Concern
4 4
5 5 module ClassMethods
6   - # Count operates using three different approaches.
7   - #
8   - # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
9   - # * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
10   - # * Count using options will find the row count matched by the options used.
11   - #
12   - # The third approach, count using options, accepts an option hash as the only parameter. The options are:
13   - #
14   - # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
15   - # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
16   - # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
17   - # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
18   - # Pass <tt>:readonly => false</tt> to override.
19   - # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
20   - # to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
21   - # See eager loading under Associations.
22   - # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
23   - # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
24   - # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
25   - # include the joined columns.
26   - # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
27   - # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
28   - # of a database view).
29   - #
30   - # Examples for counting all:
31   - # Person.count # returns the total count of all people
32   - #
33   - # Examples for counting by column:
34   - # Person.count(:age) # returns the total count of all people whose age is present in database
35   - #
36   - # Examples for count with options:
37   - # Person.count(:conditions => "age > 26")
38   - # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
39   - # Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins.
40   - # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
41   - # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
42   - #
43   - # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
44   - def count(*args)
45   - case args.size
46   - when 0
47   - construct_calculation_arel.count
48   - when 1
49   - if args[0].is_a?(Hash)
50   - options = args[0]
51   - distinct = options.has_key?(:distinct) ? options.delete(:distinct) : false
52   - construct_calculation_arel(options).count(options[:select], :distinct => distinct)
53   - else
54   - construct_calculation_arel.count(args[0])
55   - end
56   - when 2
57   - column_name, options = args
58   - distinct = options.has_key?(:distinct) ? options.delete(:distinct) : false
59   - construct_calculation_arel(options).count(column_name, :distinct => distinct)
60   - else
61   - raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
62   - end
63   - rescue ThrowResult
64   - 0
65   - end
66   -
67   - delegate :average, :minimum, :maximum, :sum, :to => :scoped
  6 + delegate :count, :average, :minimum, :maximum, :sum, :to => :scoped
68 7
69 8 # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
70 9 # Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
65 activerecord/lib/active_record/relation/calculation_methods.rb
... ... @@ -1,8 +1,55 @@
1 1 module ActiveRecord
2 2 module CalculationMethods
3   -
4   - def count(*args)
5   - calculate(:count, *construct_count_options_from_args(*args))
  3 + # Count operates using three different approaches.
  4 + #
  5 + # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
  6 + # * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
  7 + # * Count using options will find the row count matched by the options used.
  8 + #
  9 + # The third approach, count using options, accepts an option hash as the only parameter. The options are:
  10 + #
  11 + # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
  12 + # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
  13 + # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
  14 + # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
  15 + # Pass <tt>:readonly => false</tt> to override.
  16 + # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
  17 + # to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
  18 + # See eager loading under Associations.
  19 + # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
  20 + # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
  21 + # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
  22 + # include the joined columns.
  23 + # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
  24 + # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
  25 + # of a database view).
  26 + #
  27 + # Examples for counting all:
  28 + # Person.count # returns the total count of all people
  29 + #
  30 + # Examples for counting by column:
  31 + # Person.count(:age) # returns the total count of all people whose age is present in database
  32 + #
  33 + # Examples for count with options:
  34 + # Person.count(:conditions => "age > 26")
  35 + # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
  36 + # Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins.
  37 + # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
  38 + # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
  39 + #
  40 + # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
  41 + def count(column_name = nil, options = {})
  42 + column_name, options = nil, column_name if column_name.is_a?(Hash)
  43 + column_name = select_for_count unless column_name
  44 + distinct = options.delete(:distinct)
  45 +
  46 + if options.any?
  47 + calculation_relation(options).count(column_name, :distinct => distinct)
  48 + else
  49 + relation_for_association_calculations.calculate(:count, column_name || :all, :distinct => distinct)
  50 + end
  51 + rescue ThrowResult
  52 + 0
6 53 end
7 54
8 55 # Calculates the average value on a given column. The value is returned as
@@ -73,12 +120,16 @@ def calculation_relation(options = {})
73 120 if options.present?
74 121 apply_finder_options(options.except(:distinct)).calculation_relation
75 122 else
76   - (eager_loading? || includes_values.present?) ? construct_relation_for_association_calculations : self
  123 + relation_for_association_calculations
77 124 end
78 125 end
79 126
80 127 private
81 128
  129 + def relation_for_association_calculations
  130 + (eager_loading? || includes_values.present?) ? construct_relation_for_association_calculations : self
  131 + end
  132 +
82 133 def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
83 134 column = if @klass.column_names.include?(column_name.to_s)
84 135 Arel::Attribute.new(@klass.unscoped, column_name)
@@ -196,5 +247,11 @@ def get_projection_name_from_chained_relations
196 247 @select_values.join(", ") if @select_values.present?
197 248 end
198 249
  250 + def select_for_count
  251 + if @select_values.present?
  252 + select = @select_values.join(", ")
  253 + select if select !~ /(,|\*)/
  254 + end
  255 + end
199 256 end
200 257 end
7 activerecord/lib/active_record/relation/finder_methods.rb
@@ -56,12 +56,17 @@ def find_with_associations
56 56 def construct_relation_for_association_calculations
57 57 including = (@eager_load_values + @includes_values).uniq
58 58 join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, including, arel.joins(arel))
59   - construct_relation_for_association_find(join_dependency)
  59 +
  60 + relation = except(:includes, :eager_load, :preload)
  61 + apply_join_dependency(relation, join_dependency)
60 62 end
61 63
62 64 def construct_relation_for_association_find(join_dependency)
63 65 relation = except(:includes, :eager_load, :preload, :select).select(@klass.send(:column_aliases, join_dependency))
  66 + apply_join_dependency(relation, join_dependency)
  67 + end
64 68
  69 + def apply_join_dependency(relation, join_dependency)
65 70 for association in join_dependency.join_associations
66 71 relation = association.join_relation(relation)
67 72 end

0 comments on commit 73b179e

Please sign in to comment.
Something went wrong with that request. Please try again.