Skip to content
This repository
Browse code

Ensure calculations respect scoped :select [#1334 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
commit 6543426c73fa9ccf3649d7cbacbbb0fda9b6a099 1 parent ccb0a92
authored lifo committed
18  activerecord/lib/active_record/calculations.rb
@@ -141,22 +141,30 @@ def calculate(operation, column_name, options = {})
141 141
         def construct_count_options_from_args(*args)
142 142
           options     = {}
143 143
           column_name = :all
144  
-          
  144
+
145 145
           # We need to handle
146 146
           #   count()
147 147
           #   count(:column_name=:all)
148 148
           #   count(options={})
149 149
           #   count(column_name=:all, options={})
  150
+          #   selects specified by scopes
150 151
           case args.size
  152
+          when 0
  153
+            column_name = scope(:find)[:select] if scope(:find)
151 154
           when 1
152  
-            args[0].is_a?(Hash) ? options = args[0] : column_name = args[0]
  155
+            if args[0].is_a?(Hash)
  156
+              column_name = scope(:find)[:select] if scope(:find)
  157
+              options = args[0]
  158
+            else
  159
+              column_name = args[0]
  160
+            end
153 161
           when 2
154 162
             column_name, options = args
155 163
           else
156 164
             raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
157  
-          end if args.size > 0
158  
-          
159  
-          [column_name, options]
  165
+          end
  166
+
  167
+          [column_name || :all, options]
160 168
         end
161 169
 
162 170
         def construct_calculation_sql(operation, column_name, options) #:nodoc:
11  activerecord/test/cases/calculations_test.rb
@@ -264,6 +264,17 @@ def test_should_count_selected_field_with_include
264 264
     assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
265 265
   end
266 266
 
  267
+  def test_should_count_scoped_select
  268
+    Account.update_all("credit_limit = 50")
  269
+    assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count
  270
+  end
  271
+
  272
+  def test_should_count_scoped_select_with_options
  273
+    Account.update_all("credit_limit = 50")
  274
+    Account.first.update_attribute('credit_limit', 49)
  275
+    assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count(:conditions => [ 'credit_limit >= 50'] )
  276
+  end
  277
+
267 278
   def test_should_count_manual_select_with_include
268 279
     assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm)
269 280
   end

0 notes on commit 6543426

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