Module: MakeTaggable::Taggable::Related::CalculationMethods

Defined in:
lib/make_taggable/taggable/related.rb

Overview

These relations select the taggable's columns plus an aliased count, and order by that alias. Active Record folds the select list into the COUNT() it builds, which produced SQL no adapter accepts:

SELECT COUNT(taggable_models.*, COUNT(tags.id) AS count) ...

Counting rows instead is not enough on its own either: the relation groups by primary key over a cross join, so dropping the grouping counts taggings rather than records, and the ORDER BY still names an alias that a bare COUNT(*) no longer selects.

So count the grouped query as a subquery. klass.unscoped is the shell for it because it carries no extension of its own -- counting a relation derived from this one would re-enter this method.

Instance Method Summary collapse

Instance Method Details

#count(column_name = :all) ⇒ Integer

The number of related records.

Parameters:

  • column_name (Symbol, String) (defaults to: :all)

    accepted for signature compatibility; ignored

Returns:

  • (Integer)


159
160
161
162
163
# File 'lib/make_taggable/taggable/related.rb', line 159

def count(column_name = :all)
  ids = except(:select, :order).select(Arel.sql("#{klass.table_name}.#{klass.primary_key}"))

  klass.unscoped.from(Arel.sql("(#{ids.to_sql}) AS #{klass.table_name}_related")).count(:all)
end

#sizeInteger

Returns the number of related records.

Returns:

  • (Integer)

    the number of related records



168
169
170
# File 'lib/make_taggable/taggable/related.rb', line 168

def size
  loaded? ? to_a.size : count
end