Class: ActiveRecord::Associations::AssociationCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/octopus/association_collection.rb

Instance Method Summary collapse

Instance Method Details

#count(column_name = nil, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/octopus/association_collection.rb', line 6

def count(column_name = nil, options = {})
  if @reflection.options[:counter_sql]
    if should_wrap_the_connection?
      @owner.using(@owner.current_shard) { @reflection.klass.count_by_sql(@counter_sql) } 
    else        
      @reflection.klass.count_by_sql(@counter_sql)
    end
  else
    column_name, options = nil, column_name if column_name.is_a?(Hash)

    if @reflection.options[:uniq]
      # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
      column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" unless column_name
      options.merge!(:distinct => true)
    end

    value = @reflection.klass.send(:with_scope, construct_scope) do 
      if should_wrap_the_connection?
        @owner.using(@owner.current_shard) { @reflection.klass.count(column_name, options) } 
      else        
        @reflection.klass.count(column_name, options) 
      end
    end

    limit  = @reflection.options[:limit]
    offset = @reflection.options[:offset]

    if limit || offset
      [ [value - offset.to_i, 0].max, limit.to_i ].min
    else
      value
    end
  end
end

#should_wrap_the_connection?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/octopus/association_collection.rb', line 2

def should_wrap_the_connection?
  @owner.respond_to?(:current_shard) && @owner.current_shard != nil
end